Is there a way in Log4Net or NLog (or some other kind of log) for outputting logs in XML format with an attached stack or in JSON format?

Is there a way in Log4Net or NLog (or some other kind of log) for outputting logs in XML with an attached stack or in JSON format, so if the A() function calls B(7) , which calls C("something") , this' Output something like:

 <Method name="A"> <Method name="B" params="(int) 7"> <Method name="C" params="(string) 'something'"/> </Method> </Method> 

or even better:

 <Method name="A"> <Method name="B" params="(int) 7"> <Params> <int>7</int> </Params> <Method name="C"> <Params> <string>something</string> </Params> </Method> </Method> </Method> 

Why? so I could use (for example) XML Notepad or some JSON -viewer (I don’t know any great ...) to quickly add (irrelevant) or expand (relevant) sub-selections, trying to understand what went wrong. I use PostSharp to write (currently using indentation) each input / output method and exceptions

+6
source share
3 answers

The logging structure does not contain information about the boundaries of your method, and therefore, it cannot format XML accordingly. You can try to expand the structure and pass additional information to logging methods.

An easier way to get this conclusion is to do all the formatting of the messages in your class aspect and configure the logging structure to display only the text of the message without any other information.

For example, in the log4net configuration:

 <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%message%newline" /> </layout> 

In your OnEntry aspect , you should open the XML tag (or JSON object) and close the tag in OnExit . You can start with a simple example below and optimize the code for your specific case (for example, initialize a log instance and format strings in the RuntimeInitialize, CompileTimeInitialize methods).

 [Serializable] public class XmlLogAttribute : OnMethodBoundaryAspect { public override void OnEntry(MethodExecutionArgs args) { ILog log = LogManager.GetLogger(args.Method.DeclaringType); if (log.IsDebugEnabled) { log.DebugFormat("<Method name=\"{0}\">", args.Method.Name); log.Debug("<Params>"); foreach (object methodArgument in args.Arguments) { if (methodArgument == null) { log.Debug("<null/>"); } else { log.DebugFormat("<{0}>{1}</{0}>", methodArgument.GetType(), methodArgument); } } log.Debug("</Params>"); } } public override void OnExit(MethodExecutionArgs args) { ILog log = LogManager.GetLogger(args.Method.DeclaringType); log.Debug("</Method>"); } } 
+2
source

You will need to create your own override of the XmlLayoutBase FormatXml method in log4net.

See a similar answer here

0
source

See stacktrace log4net PatternLayout . Harvesting is obviously more expensive, but it should give some results. It is also possible to change the rendering of log information. The log4net.Ext.Json project has decorators that can be used for this. (I am the author).

0
source

All Articles