log4net的 - 自定义属性记录 [英] log4net - Custom property logging
本文介绍了log4net的 - 自定义属性记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用下面的类打印出使用log4net的消息:
I got use the following class to print out messages using 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
属性,但我不知道如何解决这个问题。
I use Logger.Info(MessageInstance)
, so log4net just invokes the ToString
method and prints out the message. I would like to also log the Id
property of the message object, but I cannot figure out how to achive this.
我的转换模式与此类似:
My conversion pattern looks similiar to this:
<conversionPattern value="%date %-5level %message%newline" />
我尝试添加%message {Id}
推荐答案
我只是写了一个自定义模式,它允许读取消息对象的属性。
I just wrote a custom pattern, which allows to read properies 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;
}
结合使用:
public class ReflectionLayoutPattern : PatternLayout
{
public ReflectionLayoutPattern()
{
this.AddConverter("item", typeof(ReflectionReader));
}
}
配置如下所示:
<layout type="MyAssembly.MyNamespace.ReflectionLayoutPattern, MyAssembly">
<conversionPattern value="[%item{Id}]	%message%newline" />
</layout>
这篇关于log4net的 - 自定义属性记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文