Question

I'm currently working with Common.Logging and log4net. I have implemented a custom appender.

I'm trying to add the layout, specified in the code below, to my logs. But when I print the function RenderLoggingEvent(loggingEvent) in my custom appender, I only get the message (but no timestamps, ...).

// 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);

If I add the configuration in the App.config file, it works. But I need a code based configuration...

Was it helpful?

Solution

You need to call ActivateOptions on the layout as well as on the appender:

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

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

Sample output:

2014-03-26 20:29:49,816 [1] DEBUG test logger (null) - log test
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top