Adding context to your logs

joysaphine @ flickr

If you have ever worked on a multi-threaded application or even any application of significant scope, one of the unwritten requirement is a log file that helps in supporting the application.

The challenge is to be able to piece together all the scattered log entries that belong together, may be as a single transaction, or a user’s session. So the goal is to have a unique identifier in each log entry that will aid greping. If you have ever faced this, you either did it cleanly as I will detail below, or you had to hack in a ‘context’ to each log entry by appending / prefixing some unique id.

I will talk about the two most commonly used logging frameworks are Apache’s log4j and log4net.

The bad (obvious) way: + " I am doing something important");
logger.debug(uid + " I am doing something else");

The problems with this approach are

  • might not have access to the uid in each function that is called
  • need to remember to append the uid everywhere
  • no way to do it in common code, utility libraries, etc.

The good news is, support for such a use case is baked into log4j and log4net.