# Friday, 20 February 2009

One of our applications has a Windows service in it. To make debugging and running this service easy,we have a winform in the service which can be activated by passing a command line switch. Simple enough. Our service does all its logging with log4net. I wanted to be able to put the output of the logging on our development form, but how?

After looking at various things, I realized what I needed to do was create a log4net appender, and add the appender to the log4net logger and at regular intervals, grab the contents of the logger.


I created the below appender which uses a StringBuilder as the backing store. It takes in one bool param in the contructor which allows you to specify if you want the log to be built up in reverse.  This is useful if you want to display the most recent event at the top.

public class StringBuilderAppender : log4net.Appender.AppenderSkeleton
    private System.Text.StringBuilder _builder = new System.Text.StringBuilder();
    private readonly bool _invert;

    public StringBuilderAppender(bool invert) { _invert = invert; }

    public string Text { get { return _builder.ToString(); } }

    protected override void Append(log4net.Core.LoggingEvent loggingEvent)
        var msg = loggingEvent.RenderedMessage;
        if (_invert)
            _builder = new System.Text.StringBuilder().AppendLine(msg).Append(_builder);

Now we need to add our new appender to the logger. I found this helper method someone wrote.

public static void AddAppender(string loggerName, IAppender appender)
    log4net.ILog log = log4net.LogManager.GetLogger(loggerName);
    log4net.Repository.Hierarchy.Logger l = (log4net.Repository.Hierarchy.Logger)log.Logger;


Finally, lets put it all together:

StringBuilderAppender appender = new StringBuilderAppender(true);
AddAppender("MyLogger", appender);

while(true) {
    someControl.Text = appender.Text;
.NET | HowTo | Logging
Friday, 20 February 2009 22:18:15 (Alaskan Standard Time, UTC-09:00)