在Common.Logging中配置布局

时间:2014-03-26 16:17:06

标签: c# log4net appender common.logging

我目前正在使用Common.Logging和log4net。我已经实现了自定义appender。

我试图将下面代码中指定的布局添加到我的日志中。但是当我在自定义appender中打印函数RenderLoggingEvent(loggingEvent)时,我只收到消息(但没有时间戳,......)。

// create properties
// EXTERNAL expects log4net being configured somewhere else in
// your code and does nothing.
NameValueCollection properties = new NameValueCollection();
properties["configType"] = "EXTERNAL";

// set Adapter
Common.Logging.LogManager.Adapter = 
    new Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter(properties);

// create an object of the custom appender
var appender = new SimpleAppender();
appender.Name = "SimpleAppender";

// add layout to the appender
var layout = new log4net.Layout.PatternLayout()
{
    ConversionPattern = 
        "%date [%thread] %-5level %logger %ndc - %message%newline"
};
appender.Layout = layout;

//Let log4net configure itself based on the values provided
appender.ActivateOptions();
log4net.Config.BasicConfigurator.Configure(appender);

如果我在App.config文件中添加配置,它可以正常工作。但我需要一个基于代码的配置......

1 个答案:

答案 0 :(得分:2)

您需要在布局和appender上调用ActivateOptions

var layout = new log4net.Layout.PatternLayout()
{
    ConversionPattern = 
        "%date [%thread] %-5level %logger %ndc - %message%newline"
};

layout.ActivateOptions();
appender.Layout = layout;

示例输出:

2014-03-26 20:29:49,816 [1] DEBUG test logger (null) - log test