logging – Andy Palmer https://andypalmer.com Views on software, technology, consulting and business process Fri, 22 May 2009 13:09:10 +0000 en-US hourly 1 https://wordpress.org/?v=6.4.3 Well, how did I get here? https://andypalmer.com/2008/08/well-how-did-i-get-here/ https://andypalmer.com/2008/08/well-how-did-i-get-here/#respond Mon, 25 Aug 2008 11:47:00 +0000 http://www.andypalmer.com/blog/?p=11
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);
}
doWhatWeNeedToDoWith(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.

]]>
https://andypalmer.com/2008/08/well-how-did-i-get-here/feed/ 0