[英]log4net - Custom property logging
我使用以下类使用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
属性,但是我不知道该如何实现。
我的转换模式与此类似:
<conversionPattern value="%date %-5level %message%newline" />
我尝试添加%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<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;
}
与此结合:
public class ReflectionLayoutPattern : PatternLayout
{
public ReflectionLayoutPattern()
{
this.AddConverter("item", typeof(ReflectionReader));
}
}
配置看起来像这样:
<layout type="MyAssembly.MyNamespace.ReflectionLayoutPattern, MyAssembly">
<conversionPattern value="[%item{Id}]	%message%newline" />
</layout>
您可以使用从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配置中使用此布局类:
<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>
这是主意。 有关更多特定的详细信息,您将必须查阅log4Net SDK文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.