以编程方式添加log4net appender,但布局不起作用

时间:2016-07-12 19:50:04

标签: c# log4net log4net-configuration log4net-appender

我有以下代码将滚动文件appender添加到log4net。

        ILog myLogger = LogManager.GetLogger("Audit");

        var auditAppender = new RollingFileAppender()
        {
            Name = "AuditAppender",
            File = this.fullyQualifiedFileName,
            DatePattern = "yyyyMMdd",
            RollingStyle = RollingFileAppender.RollingMode.Date,
            AppendToFile = true,
            Layout = new PatternLayout()
            {
                ConversionPattern = "%newline %date %-5level %newline%message%newline",
            },
        };

        auditAppender.ActivateOptions();

        log4net.Repository.Hierarchy.Logger l = (log4net.Repository.Hierarchy.Logger)myLogger.Logger;
        l.AddAppender(auditAppender);
        l.Repository.Configured = true;

        myLogger.Info(message);

但结果似乎并没有跟随我的ConversionPattern。任何线索?

1 个答案:

答案 0 :(得分:2)

你非常非常接近; - )

您唯一遗漏的是您还需要拨打PatternLayout.ActivateOptions

var auditAppender = new RollingFileAppender()
{
    // snip
}

((PatternLayout)auditAppender.Layout).ActivateOptions();
auditAppender.ActivateOptions();