DZone can't read your mind. Tell us what you like! Login and vote now.
By kbilsted
via firstclassthoughts.co.uk
Published: May 27 2008 / 17:39
The standard way to acquire Log4j loggers do not ensure consistency between logger name and class using the logger. Such inconsistency leads to inconsistencies in the log files, rendering any information in the log file difficult to use. This article shows how to ensure between logger name and class using the logger through usage of the Spiffy Framework.
Comments
raveman replied ago:
sorry, pointless. you can check the static version at compile time using checkstyle, etc.
kbilsted replied ago:
I'm not sure I understand your negative vote. Log4J obviously have a serious flaw in how loggers are defined. You are probably right that you can use some third-party tool to check what you've done is correct, but that does not negate the fact that the approach I suggest for acquiring loggers are easier and will ALWAYS work. Conventions are easiest upheld when they are automatic...
sproketboy replied ago:
Interesting idea.
kbilsted replied ago:
Thanks.
Yes the idea of implementing a 'thisclass' as done here can be used in a number of places. I found it really useful for the Log4J stuff, hence my blog...
behrangsa replied ago:
You can also inject the logger at runtime:
You will need some extra libs in your project though.
behrangsa replied ago:
Oops, I meant:
kbilsted replied ago:
Hi behrangsa
thanks for the comment. What framework are you using for this?
Can you make the log variable static? if not you are not much better off than using the Logger.getLogger( this.getClass() )
yardena replied ago:
IntelliJ code generation template worked for me, so I haven't really looked for other ways. Guice (http://code.google.com/p/google-guice) is supposed to be able to do this kind of things. Another trick I can think of:
class ... {final static Class me = new Whatever() {}.getClass().getEnclosingClass();
}
kbilsted replied ago:
That's a nice one, I should probably include this in the article. Its JDK5+ only isn't it?
yardena replied ago:
Yup. There is also a getDeclaringClass() http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getDeclaringClass() but one time I tried it, it didn't return what I expected.
kbilsted replied ago:
Thanks for your comments. I think its worth extending the article with annonymous subclasses and loggers.. it surely is something that you can't check with checkstyle! :-)
Voters For This Link (10)
Voters Against This Link (3)