Log4net - Register custom properties

I used the following class to print messages using log4net:

public class Message { public String Text { get; set; } public int Id { get; set; } public override string ToString() { return Text; } } 

I use Logger.Info(MessageInstance) , so log4net just calls the ToString method and displays a message. I would also like to write the Id property of the message object, but I cannot figure out how to do this.

My conversion scheme looks like this:

 <conversionPattern value="%date %-5level %message%newline" /> 

I tried adding %message{Id} , but that would just print the whole message twice.

Any suggestions?

+4
source share
2 answers

I wrote my own template, which allows you to read the properties of the message object.

 public class ReflectionReader : PatternLayoutConverter { public ReflectionReader() { _getValue = GetValueFirstTime; } protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) { writer.Write(_getValue(loggingEvent.MessageObject)); } private Func<object, String> _getValue; private string GetValueFirstTime(object source) { _targetProperty = source.GetType().GetProperty(Option); if (_targetProperty == null) { _getValue = x => "<NULL>"; } else { _getValue = x => String.Format("{0}", _targetProperty.GetValue(x, null)); } return _getValue(source); } private PropertyInfo _targetProperty; } 

Combine with this:

 public class ReflectionLayoutPattern : PatternLayout { public ReflectionLayoutPattern() { this.AddConverter("item", typeof(ReflectionReader)); } } 

The configuration looks like this:

 <layout type="MyAssembly.MyNamespace.ReflectionLayoutPattern, MyAssembly"> <conversionPattern value="[%item{Id}]&#9;%message%newline" /> </layout> 
+2
source

You can use the CustomXmlLayout class, which comes from XmlLayoutBase and overrides the FormatXml method. This method takes a LoggingEvent object as a parameter that will contain the MessageObject that was passed to the log method.

 public class SpecialXmlLayout : XmlLayoutBase { protected override void FormatXml(XmlWriter writer, LoggingEvent loggingEvent) { Message message = loggingEvent.MessageObject as Message; writer.WriteStartElement("LoggingEvent"); writer.WriteElementString("Message", GetMessage(message)); // ... write other things writer.WriteEndElement(); } } 

Inside the GetMessaage method, create your own string, as you would like, from the message.

Then use this layout class in the log4net configuration:

 <log4net> <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender"> <applicationName value="My Application" /> <layout type="Namespace.SpecialXmlLayout"> </layout> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="ERROR" /> <param name="LevelMax" value="FATAL" /> </filter> </appender> </log4net> 

This is an idea. For more information, you need to refer to the log4Net SDK documentation.

+2
source

All Articles