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?
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.
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.
Log4net is a synchronous engine.
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.
I have been using the BasicConfigurator configured with a MemoryAppender. This appender lets you get to the in-memory messages logged during your test.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With