Intercept Log4Net message in a Windows application

Scenario: I have some service that runs in the background, but I want the user to be able to launch interactively with a  windows form application and I want to intercept all log4net messages issued by the various components that works in the background.

Thanks to the supereasy way to write an appender in log4net, obtaining this result is really simple..

   1: public class Log4NetLogEventSourceAppender : AppenderSkeleton

   2:    {

   3:        private Object _syncRoot;

   4:  

   5:        public Log4NetLogEventSourceAppender()

   6:        {

   7:            _syncRoot = new object();

   8:        }

   9:  

  10:        /// <summary>

  11:        /// Occurs when [on log].

  12:        /// </summary>

  13:        public static event EventHandler<OnLog4NetLogEventArgs> OnLog;

  14:  

  15:        protected override void Append(LoggingEvent loggingEvent)

  16:        {

  17:            EventHandler<OnLog4NetLogEventArgs> temp = OnLog;

  18:            if (temp != null)

  19:            {

  20:                lock (_syncRoot)

  21:                {

  22:                    temp(null, new OnLog4NetLogEventArgs(loggingEvent));

  23:                }

  24:            }

  25:        }

  26:  

  27:    }

  28:  

  29:    public class OnLog4NetLogEventArgs : EventArgs

  30:    {

  31:        public LoggingEvent LoggingEvent { get; private set; }

  32:  

  33:        public OnLog4NetLogEventArgs(LoggingEvent loggingEvent)

  34:        {

  35:            LoggingEvent = loggingEvent;

  36:        }

  37:    }

This is a quick and dirty approach, a _syncRoot object will serialize all events because this is a shared event I want to prevent multiple threads to messup logging. Thanks to the shared event you can simply add this appender to the list of enabled appender.

   1: <appender

   2:     name="Interceptor"

   3:     type="xxx.Log4NetLogEventSourceAppender, xxx">

   4:     <layout type="log4net.Layout.PatternLayout">

   5:       <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline %property{analyzing_url}" />

   6:     </layout>

   7:   </appender>

Now in code you should simply subscribe to appender event.

   1: Log4NetLogEventSourceAppender.OnLog += Log4NetLogEventSourceAppender_OnLog;

And do something useful in the event handler, in my program I have a custom MVP pattern, and I simply add the log the to the view (that in turn shows a grid with all the logs with filtering and sorting capabilities).

   1: void Log4NetLogEventSourceAppender_OnLog(object sender, OnLog4NetLogEventArgs e)

   2: {

   3:      View.AppendLog(e.LoggingEvent);

   4: }

Thanks to the extremely flexibility of log4net it is possible to manage logs in a great variety of locations, and with this simple interceptor you can propagate logging wherever you want.

Another useful application of this logger was made in a scheduled service,

   1: private void ReactToLogMessages(OnLog4NetLogEventArgs e, StringBuilder log4netLogs, ScanLog scanLog)

   2: {

   3:     if (e.LoggingEvent.Level >= log4net.Core.Level.Info)

   4:     {

   5:         log4netLogs.AppendLine(e.LoggingEvent.RenderedMessage);

   6:     }

   7:     //ora capire il livello di errore

   8:     if (e.LoggingEvent.Level == log4net.Core.Level.Warn)

   9:     {

  10:         scanLog.NumOfWarnings++;

  11:     }

  12:     else if (e.LoggingEvent.Level == log4net.Core.Level.Error)

  13:     {

  14:         scanLog.NumOfErrors++;

  15:     }

  16: }

This function simply append all info or greater logs to a string, but the most important fact is that he count the number of warning and errors, and after the task finish, it warn the administrator if there are errors or more than a certain number of warning. This will make simple to react to task that have problems.

Alk.

Published by

Ricci Gian Maria

.Net programmer, User group and community enthusiast, programmer - aspiring architect - and guitar player :). Visual Studio ALM MVP

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.