Logging with log4net

Published Fri, May 20 2005 8:30 PM

Do you log in your application ? Have you written custom code to log to a file or database or anything else ?
If you ask me it's a wast of time! You could use EIF, Enterprise Library or Log4Net.

Till now Log4Net is my favorite because it's easy, fast, flexible and fits my needs. Log4net is an assembly that allows programmers to log statements to a variety of output targets. Log4Net provides 5 log levels by default. Debug, Info, Warn, Error and Fatal.

Every output target is called an appender. There are about 20 appenders available by default like: file, eventlog, console, database, udp, etc. You can append your log statements to one or more appenders on the same time. For example: 
-log Debug and Info statements to a logfile
-log Warn, Error and Fatal statements to the database.
-And besides this send fatal log statements as an email.

Log4Net is open source so when you would like to have a sms-appender. Just add it. (and send my a copy :-))

Besides the appenders also the way you format your log statements to the output devices is configurable. For example as Xml or format it with a pattern. Everything is configurable in xml. Log4Net is fast and Flexible. Log4Net can capture data in a context which allows you to log statements for each logging message. This is a little vague so an example:

In your multithreading application you have a process that has an id which allows you do identify the message it's processing at this time. The 'messageId'.
As soon as the messageId becomes available you add it as a dynamic property to log4Net. Every log statement after this can add this property to the log statement.

for example you could log:
log.Info(string.Format("Beginning my advanced process for message [{0}]", messageId))   // logs: Beginning my advanced process for message [456]

but when you log:
log.Info("Finished Process")

you don't know which process has finished. (because of the multithreading an other process could be finished with processing the message)
In this case you have to log messageId every time when you log a statement.

log4net allows you to put this id in a property and you can configure log4net to use the property in every logstatement.

log4net.MDC.Set("MessageIdentifier", messageId)
log.Info("Beginning my advanced process")  // logs: [456] Beginning my advanced process
log.Info("Finished Process")                         // logs: [789] Finished Process

See: it was another process which finished ;-)

I could write a nice article about all this and much more features, but that's already done: http://www.ondotnet.com/pub/a/dotnet/2003/06/16/log4net.html?page=1

Filed under:

Comments

# TrackBack said on Wednesday, June 15, 2005 10:28 AM

Logging with log4netooeess

Leave a Comment

(required) 
(required) 
(optional)
(required) 
Please add 4 and 2 and type the answer here: