Log4Net Custom Appender

July 23, 2008 · 2 minute read

Log4Net is an excellent logging framework which neatly separates the specifics of your logging implementation from your business logic.

The upshot is that you can write code such as

  1. Log.Error("An error occured")

in your code, and configure the logging somewhere else (usually app/web.config).

To actually process the output you use Appenders. Log4Net has several built in appenders for logging to a file, sending email, writing to a database etc.

Occasionally you may have a reason to do something not covered by the default appenders.

In that case one option is to create your own custom appender.

To do this create a class which inherits AppenderSkeleton.

  1. ///
  2. ///Demo of custom log4net appender
  3. ///
  4. public class FooAppender : AppenderSkeleton
  5. {
  6.     protected override void Append(LoggingEvent loggingEvent)
  7.     {
  8.         // Do something with the logged data
  9.     }
  10. }

By overriding the Append method, you can write your own code to handle the logging event which Log4Net sends to the appender.

NB: You can pass any object through the logging framework as the Log4Net’s default methods (Error, Warn, Debug etc) all accept an object as the first parameter.

In the append method you can take that object and do what you like with it.

A word of caution though, if you go down the route of casting the object to a specific type and dealing with the data that way, you are effectively introducing tightly coupled code, defeating the point of having an abstracted logging framework.

For example, the following code casts the message object as a generic list of strings.

  1. protected override void Append(LoggingEvent loggingEvent)
  2.         {
  3.             IList<string> data = loggingEvent.MessageObject as IList<string>;
  4.             if (data != null)
  5.             {
  6.                 foreach (string s in data)
  7.                 {
  8.                     // Do something with each string
  9.                 }
  10.             }
  11.         }

To configure your new appender, you simply specify it in the Log4Net section of app/web.config.

  1. <appender name="Foo"type="Utils.FooAppender, FooAppender">
  2.   <threshold value="ERROR" />
  3. appender>

Finally, you can pass “extra” information into the appender by exposing public properties on your custom appender.

  1. string _callingApp;
  2.  
  3. public string CallingApp
  4. {
  5.     get { return _callingApp; }
  6.     set { _callingApp = value; }
  7. }

And you can provide this information through app/web.config as in the example below.

  1. <appender name="Foo"type="Utils.FooAppender, FooAppender">
  2.    <threshold value="ERROR" />
  3.    <CallingApp value="FooApp" />
  4. appender>

Join the Practical ASP.NET Newsletter

Ship better Blazor apps, faster. One practical tip every Tuesday.

I respect your email privacy. Unsubscribe with one click.