转换日志级别(log4net)

时间:2014-12-29 09:01:48

标签: log4net

如果INFO日志消息包含异常,我想将INFO日志级别转换为WARN。无论如何我能做到这一点吗? (我正在将.NET4net集成到.NET应用程序中)

1 个答案:

答案 0 :(得分:0)

除非您已经包装了日志记录调用,在这种情况下您可以在将消息传递给log4net之前拦截消息,最好的办法是创建自己的appender,以便在适当时提升日志事件。由于每个appender子类都需要完全相同的代码,因此我创建了一个实际促销的扩展方法:

public static class AppenderExtensions
{
    public static LoggingEvent Promote(this LoggingEvent loggingEvent)
    {
        if (loggingEvent.Level != Level.Info 
         || loggingEvent.ExceptionObject == null)
        {
            return loggingEvent;
        }

        var data = loggingEvent.GetLoggingEventData(FixFlags.All);
        data.Level = Level.Warn;
        return new LoggingEvent(data);
    }
}

public class PromotingAdoNetAppender : AdoNetAppender
{
    protected override void Append(LoggingEvent loggingEvent)
    {
        base.Append(loggingEvent.Promote());
    }
}

public class PromotingRollingFileAppender : RollingFileAppender
{
    protected override void Append(LoggingEvent loggingEvent)
    {
        base.Append(loggingEvent.Promote());
    }
}

然后您需要做的就是在配置中声明这些appender类型:

<appender name="DatabaseAppender" 
          type="Your.Namespace.Here.PromotingAdoNetAppender">
          …