log4j and developer error

I'm certain this isn't often a best practice, but I've sacked some startup time on applications before to save lines of code. Specifically, when pasting in:

Logger logger = Logger.getLogger(MyClass.class);
...developers often forget to change "MyClass" to the current class name, and several loggers always wind up pointing at the wrong place. This Is Bad.

I've occasionally written:
static Logger logger = LogUtil.getInstance();
class LogUtil {
public Logger getInstance() {
String callingClassName = Thread.currentThread().getStackTrace()[2];
return Logger.getLogger(callingClassName);
The "2" in that code might be wrong, but the gist is there; take a performance hit to (on class load, as a static variable) automatically find the class name, so that a developer doesn't have a way to mistype this or introduce any error.

I'm generally not thrilled with losing performance to prevent developer error at runtime, but if it happens as a singleton, once? Often sounds like a good trade to me.

No comments: