log4net-自定义属性记录

Jas*_*ter 5 c# log4net log4net-configuration

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

public class Message
{
    public String Text { get; set; }
    public int Id { get; set; }
    public override string ToString()
    {
        return Text;
    }
}
Run Code Online (Sandbox Code Playgroud)

我使用Logger.Info(MessageInstance),因此log4net只是调用该ToString方法并打印出消息。我也想记录Id消息对象的属性,但是我不知道该如何实现。

我的转换模式与此类似:

<conversionPattern value="%date %-5level %message%newline" />
Run Code Online (Sandbox Code Playgroud)

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

有什么建议么?

Jas*_*ter 3

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

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;
}
Run Code Online (Sandbox Code Playgroud)

与此结合:

public class ReflectionLayoutPattern : PatternLayout
{
    public ReflectionLayoutPattern()
    {
        this.AddConverter("item", typeof(ReflectionReader));
    }
}
Run Code Online (Sandbox Code Playgroud)

配置看起来像这样:

<layout type="MyAssembly.MyNamespace.ReflectionLayoutPattern, MyAssembly">
  <conversionPattern value="[%item{Id}]&#9;%message%newline" />
</layout>
Run Code Online (Sandbox Code Playgroud)