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
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.
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.
To configure your new appender, you simply specify it in the Log4Net section of app/web.config.
Finally, you can pass “extra” information into the appender by exposing public properties on your custom appender.
And you can provide this information through app/web.config as in the example below.