I recently had to whip up a small diagnostics application for a client. We were having some connection problems with a component so we wanted to wrap a WinForms GUI around the component and display some debugging information to try and diagnose it.
The component was already configured to do some logging using log4net. The GUI was going to do some additional logging of status information directly in the UI. The end result was a textbox in the GUI and a log file generated with log4net. Not bad, but the client asked if we could log everything (specifically, the log4net output) into the GUI – i.e. a single place to review all of the log messages.
It took a little bit of searching, but I found an easy way to programmatically add a root appender. All I needed was an object that implemented IAppender. Since this was quick-and-dirty and I didn't have a lot of time, my solution was as follows:
The main GUI form implemented IAppender:
This interface has a single method – DoAppend. Implementing this interface doesn't give you all of the bells and whistle's (like PatternLayout or filtering– derive from AppenderSkeleton if you're looking for that), but since this was done in the interest of speed, a quick String.Format was all I needed:
The ReportProgress method simple appends messages to a textbox in the GUI.
Finally, in my application's "main", I initialize log4net and then add the main form to the collection of root appenders:
Success! My log4net messages now appear live in the GUI as the components logs them.