2014-03-26 73 views
1

我目前正在使用Common.Logging和log4net。我已經實現了一個自定義的appender。在Common.Logging中配置佈局

我想將下面的代碼中指定的佈局添加到我的日誌中。但是,當我在自定義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文件中添加配置,它將起作用。但我需要一個基於代碼的配置...

回答

2

你需要調用佈局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