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
- 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.
- ///
- ///Demo of custom log4net appender
- ///
- public class FooAppender : AppenderSkeleton
- {
- protected override void Append(LoggingEvent loggingEvent)
- {
- // Do something with the logged data
- }
- }
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.
- protected override void Append(LoggingEvent loggingEvent)
- {
- IList<string> data = loggingEvent.MessageObject as IList<string>;
- if (data != null)
- {
- foreach (string s in data)
- {
- // Do something with each string
- }
- }
- }
To configure your new appender, you simply specify it in the Log4Net section of app/web.config.
- <appender name="Foo"type="Utils.FooAppender, FooAppender">
- <threshold value="ERROR" />
- appender>
Finally, you can pass “extra” information into the appender by exposing public properties on your custom appender.
- string _callingApp;
- public string CallingApp
- {
- get { return _callingApp; }
- set { _callingApp = value; }
- }
And you can provide this information through app/web.config as in the example below.
- <appender name="Foo"type="Utils.FooAppender, FooAppender">
- <threshold value="ERROR" />
- <CallingApp value="FooApp" />
- appender>