Tag Archives: logging

Well, how did I get here?

And you may find yourself living in a shotgun shack
And you may find yourself in another part of the world
And you may find yourself behind the wheel of a large automobile
And you may find yourself in a beautiful house, with a beautiful wife
And you may ask yourself, “Well… how did I get here?”

Once in a Lifetime – Talking Heads

Logging a Stack Trace in log4j

A while ago, I was trying to replace a number of hard coded strings with an appropriate Enum. Unfortunately, the design of the code I was working on meant that it was difficult to find all the possible values for the strings.
I decided that the behaviour that I wanted was:

  • If the string method was called with a new value, log that value, so that I can make a decision about whether I wish to add it to the Enum
  • If the string method was called with a value that matched a value in the Enum, I wanted a stack trace, so I could replace that call with the appropriate Enum call

The code I ended up with was something like this:

public void doSomething(String theDestination) {
if(weKnowAbout(theDestination)) {
logger.debug("doSomething called with a known destination of " + theDestination, new Throwable());
else {
logger.debug("doSomething called with unknown destination of " + theDestination);

Passing the new Throwable() into log4j creates a stack trace in the log output. I’ve found a number of places that tell you how to do this (now that I know how to do it), but it took me quite a bit of searching when I was first looking.