我使用以下类使用 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>
关于c# - log4net - 自定义属性日志记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15806793/