Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
658 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...