Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.
I've written previously about using log4net to log system events for diagnostic purposes in development and live environments and how its configuration is so flexible the output can be sent anywhere. Well, recently, I've been developing a client-server application that uses WSE 3.0 to communicate using web messages and to make the initial development simpler we opted to host the server component in a Windows Form so it can be easily started and stopped. I figured that since we had already littered the server with appropriate logging that we might as well show this in the server's GUI and watch the live diagnostic information as messages are received and processed.
Due to log4net's clean, modular design it is quite simple to achieve what I need.
First, we need to configure the app.config to send log entries to a MemoryAppender by adding a new appender to the log4net section
<appender name="LogViewerDemo" type="log4net.Appender.MemoryAppender"> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" /> </layout></appender>
and specifying the appender name in the root section:
<appender-ref ref="LogViewerDemo" />
Next we write a UserControl containing a RichTextBox and a Timer. Every second, the timer will ask log4net for the MemoryAppender with the name 'LogViewerDemo' and output any new events received since the last timer tick to the RichTextBox.
Obtaining the MemoryAppender:
Hierarchy loggerHierarchy = LogManager.GetRepository() as Hierarchy;if (loggerHierarchy != null){ logMemoryAppender = loggerHierarchy.Root.GetAppender(appenderName) as MemoryAppender;}
Fetching the log events:
LoggingEvent[] events = logMemoryAppender.GetEvents();logMemoryAppender.Clear();foreach (LoggingEvent logEvent in events){ WriteLogEventToLogTextBox(logEvent);}
Finally, all that is left is to append the event details to the end of the RichTextBox having first coloured the text red, orange or black to indicate the logging levels of 'Error', 'Warning' and 'anything else' respectively.
Log4NetViewerDemo.zip (13.91 KB)
Remember Me