c# - log4net - 自定义属性日志记录

标签 c# log4net log4net-configuration

我使用以下类使用 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}]&#9;%message%newline" />
</layout>

关于c# - log4net - 自定义属性日志记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15806793/

相关文章:

带有 .NET Core 应用程序的 Log4Net 配置

log4net 日志文件未使用 Quartz.net + Common.Logging 写入

c# - 是否可以以分层方式配置 log4net,类似于 .NET 环境处理 app.config 或 web.config 的方式

c# - 如何在 C# 中的警告框确定按钮上编写操作?

c# - 如何使用 C# 泛型比较类型?

.net - 即使浏览器站点关闭,Log4net 文件也会被锁定

c# - 为什么没有读取 log4net 配置文件

c# - sqlite 只支持 1 个事务?

c# - 我如何更改此代码以使其停止循环但显示相同的内容?

.net - log4net 日志记录 Debug.WriteLine 和 Console.WriteLine