Friday, April 17, 2009

Getting going with log4net

All the previous posts were about things I've done (and not everything I've done - they'll make nice future filler). I'll be typing this one up as I go through the learning curve, so there should be more detail for you bit-heads out there.

I've used log4net, and variations thereof (there's a log4*, it seems). Logging facilities and levels are very configurable, and adaptable to almost any need.

For example (and you'll see this one everywhere):
<log4net>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="ConsoleAppender" />
</root>
<logger name="Spring">
<level value="INFO" />
<appender-ref ref="ConsoleAppender" />
</logger>
</log4net>

An "appender" is your output, the console in this case. You can get color console output, if you like (love it!). There's also files, rolling files, Event Log, database, SMTP, and more appenders.

Next is our "layout" - what do we want the log entries to look like? This uses the very flexible "PatternLayout", which lets you use "%whatever" to format the output.

Then you've got your "root" element. These are the default logger settings.

Next, we have named logger, "Spring". An application can use this log by name, and its output can be somewhere else entirely.

From the developer's standpoint, things look like this:
Logger.Info( "informative message");
Logger.Warn( "warning message" );
Logger.Error( "error message" );

They don't have to know where they're writing their messages, or whether or not they are writing their message at all. If everybody uses named loggers, then you, the poor IT guy who gets called when it all breaks down, don't have to waste your time waiting for a developer to wake up, too. Just crank up logging wherever it seems appropriate, and dig on in.

Even better, when it comes time to move it, the necessary changes are obvious.

I know that there a lot of shops out there that will claim to be doing this. Many of them are, if "including the library in the project" counts. If you're not seeing this level of granularity, question why, and insist on it. It doesn't have to be log4net, but it should be very configurable.

Back on topic...

O'Reilly provides a nice tutorial.
The real dirt can be found at log4net's home at the ASF.

No comments:

Post a Comment