Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically adding and removing log appenders in log4net

Tags:

I have a component that uses log4net. I want to create unit tests, that validate that certain error conditions result in the correct logging.

I was thinking that the best way to do this is to create an ILogAppender implementation, for example a mock. I would then add the log appender to log4net during test setup, inspect what was written during test validation, and remove it again during test teardown.

Is this possible?

like image 330
Pete Avatar asked Oct 05 '09 12:10

Pete


People also ask

How do I use multiple Appenders in log4net?

You can't log to separate appenders - you need to configure different loggers, and attach the appropriate appender to each one. Then log different messages to the different loggers.

What are log4net Appenders?

For log4net to know where to store your log messages, you add one or more appenders to your configuration. An appender is a C# class that can transform a log message, including its properties, and persist it somewhere. Examples of appenders are the console, a file, a database, an API call, elmah.io, etc.

Is log4net asynchronous?

Log4net is a synchronous engine.


2 Answers

Using the BasicConfigurator is fine for unit testing (what the OP asked for, but not what's in the subject line). The other answers grab output for a specific logger.

I wanted it all (this was a 'self test' page within a website). In the end I did basically the following:

var root = ((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root; var attachable = root as IAppenderAttachable;  var appender = new log4net.Appender.MemoryAppender(); if(attachable!=null)     attachable.AddAppender(appender); // do stuff var loggingEvents = appender.GetEvents(); foreach (var loggingEvent in loggingEvents)     loggingEvent.WriteRenderedMessage(writer); if(attachable!=null)     attachable.RemoveAppender(appender); 

...but wrapped up as a Disposable as per @Pawel's approach

UPDATE: Pawel's answer was deleted, so I am adding his link here: Programmatically check Log4Net log.

like image 55
piers7 Avatar answered Sep 22 '22 00:09

piers7


I have been using the BasicConfigurator configured with a MemoryAppender. This appender lets you get to the in-memory messages logged during your test.

like image 40
Peter Lillevold Avatar answered Sep 22 '22 00:09

Peter Lillevold