views:

92

answers:

2

I'm fairly new to log4net, and I can't seem to find any clear examples of how to handle this situation.

I have a communication stack that consists of three layers: hardware, transport, and protocol. The three layers are contained inside of a manager class. As far as the user of the code is concerned they create the manager with a hardware type (Serial,Ethernet,SSL,etc) and provide an address. There can be multiple manager instances, each connecting to a different target.

I'd like my output to give context of which connection the particular message came from (127.0.0.1 or COM5 etc). The ThreadContext isn't much use because the manager can be called from any thread and each layer runs on its own thread.

Is there any way to set a context based on a particular instance of an object? Or is there a better way to handle the output formatting?

A: 

You should use an overload of LogManager.GetLogger() that takes string name, this way you can pass pretty much anything as the logger name.

zvolkov
I've looked into that method, but if I do that I have to be sure to pass the connection info into all of the different layers. I was hoping to avoid exposing that type of stuff. If that's the only way though, it will have to do.
kyork
+1  A: 

A way of adding additional per-message context is to not only log a string message but create your own message object containing both log information and the connection hardware type (and any additional information you would like to include).

You can find an example of this here.

Another option could be using a Nested Diagnostics Context:

using(NDC.Push("<Connection type>"))
{
     // perform your logging here
}

The NDC data will be included with the message and can be output with the %ndc pattern. A note of warning though, the NDC will be included with ANY messages logged within its using scope, which is perhaps why you would consider going the custom message route.

Peter Lillevold