views:

96

answers:

2

Hi,

This is my first question on stack overflow. I haven't had much luck finding an answer via google or stackoverflow.

I'm interested in having an nunit test examine the log4net for a specific entry in the log and assert based on the results of that search.

Based on an unrelated post I read re: log4net, I think I can probably use MemoryAppender to do this via the GetEvents method and perusing the array of events returned.

But I'm wondering: 1. Has anyone done this? Any pitfalls or suggestions? Any alternate approaches? 2. Does any have a recipe they could present?

Thanks.

+1  A: 

Take a look at this SO post.

Peter Lillevold
A: 

Ok, answering my own question (or rather, my co-worker is, thanks Beth).

In your configuration for log4net: config:

<log4net>
     <appender name="MemoryAppender" type="log4net.Appender.MemoryAppender" />
     <root>
     <level value="DEBUG" />
     <appender-ref ref="MemoryAppender" />
     </root>
</log4net>

In your .net code:

List<string> messages = new List<string>();
Hierarchy hierarchy = LogManager.GetLoggerRepository() as Hierarchy;
MemoryAppender appender = hierarchy.Root.GetAppender("MemoryAppender") as MemoryAppender;
LoggingEvent[] eventList = appender.GetEvents();

foreach (LoggingEvent item in eventList)
   messages.Add(item.RenderedMessage);

return messages.ToArray();

Once you have the messages array, do what you want to.

This doesn't address if you have an existing log file and want to search it.

Keith Hoffman