Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
660 views
in Technique[技术] by (71.8m points)

.net - Programmatically adding and removing log appenders in log4net

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...