Matthew Cox Team : Web Development Tags : Web Development Programming Tips & Tricks

Application logging

Matthew Cox Team : Web Development Tags : Web Development Programming Tips & Tricks

All applications require logging to some degree, whether that is simply logging to the standard output stream or asynchronously logging a fixed size rolling log file to disk using enterprise logging tools.

With the prevalence of logging it’s surprising how often I see it done wrong.

I’m of the opinion that generally when logging is done wrong it’s done from the mindset of “this seems like something I should probably log”, not “what am I trying to achieve by logging this message”.

Most often I see this in web service integration code, a particular web service will implement a series of error codes, so the developer integrating the web service says to themselves “If I get one of these error codes, I better make a note of it”.

Which is a good start, certainly it’s leagues ahead of the “swallow the error and keep going approach”, but you need to go a step further. You need to think about the maintenance programmer who will have to correlate the error back to the code.

With this in mind, for each event you need at a bare minimum at least 3 pieces of information. What the error was, when it occurred and where it occurred in code.

 

Where did it happen? That is what is important.

In my experience developers usually log the error message and when the error occurred, however when there is no way to relate the event back to where it occurred in the codebase it can be incredibly frustrating.

So how do you ensure that an error log event can be tracked back to a particular point in the codebase?

The simplest answer is to use a unique message for every logging event, and while it’s the simplest, it’s also the most error prone.

Another way to ensure uniqueness is to assign a unique event code to each logging event, but this again leads to difficulty in maintaining a unique list of error codes.

It’s for this reason that most logging components will at a minimum get the name of the calling class and append that to any log messages. See examples below:

Initialising Nlog:

private static readonly Logger _log =
LogManager.GetCurrentClassLogger();

Initialising Log4net:

private static readonly ILog _log =
LogManager.GetLogger(typeof(Program));

This is usually enough to allow a maintenance programmer to track down where the issue occurred, however I would still recommend where possible adding the name of the method that was actually being invoked as this leaves it completely unambiguous about where the error occurred.