Log4Net: Writing a C# object (apart from Exception) to the log?
I have seen in Log4Net you can wr开发者_Go百科ite a message and pass as the second parameter the Exception Object.
Is it possible to send another type of object to log4net so I can see the values in my log of my object?
If i have an instance of a class that is populate and I went to send the instance along to be logged,
Is this at all possible?
You can implement a custom formatter. (Try Googling first to see if anyone has made something that fits your scenario).
You could always write it out yourself, which gives a bit of control. You can use Reflection to get the type of the object, get the properties and write them out as Debug or Info.
You could further extend the method that gets you the properties to only write out what you want and run recursively n-levels deep into the object or until it has no properties.
The various methods of the ILog
interface accept an object as "message" parameter, therefore the easiest way to get an object "written" by log4net is to implement a ToString()
method.
Another way would be to provide an IObjectRenderer
implementation. I am not sure how to register this in a configuration file, but this shows how to do in code.
If you need the object as separate entity in an appender then you should use log event context (also works well with a ToString()
implementation.
精彩评论