log4net – 自定义属性日志记录

我使用以下类使用log4net打印消息:

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

我使用Logger.Info(MessageInstance) ,因此log4net只调用ToString方法并打印出消息。 我还想记录消息对象的Id属性,但我无法弄清楚如何实现这一点。

我的转换模式看起来与此类似:

  

我尝试添加%message{Id}但这只会打印整个消息两次。

有什么建议?

我刚刚写了一个自定义模式,它允许读取消息对象的属性。

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

结合这个:

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

Config看起来像这样:

    

您可以使用派生自XmlLayoutBase的CustomXmlLayout类并覆盖FormatXml方法。 此方法将LoggingEvent对象作为参数,该对象将包含传递给log方法的MessageObject。

 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(); } } 

在GetMessaage方法内部,您可以根据需要从消息中创建字符串。

然后在log4net config中使用此布局类:

            

这是个主意。 有关更具体的详细信息,您必须参考log4Net SDK文档。