tags:

views:

435

answers:

5

I'm working on some legacy code with a lot of code like

private final Logger logger = LogManager.getLogger(ThisClassName.class);

I'm wondering if there is any advantage to typing out "ThisClassName.class" as opposed to

LogManager.getLogger(getClass());

As far as I can tell, there is none, but I'm wondering if there are any negative ramifications to using getClass(). Thanks.

+10  A: 

If you're making the Logger static, you can't use getClass().

Michael Myers
+2  A: 

getClass() does not work from a static context. ThisClassName.class works for static and instance variables.

neesh
+5  A: 

Also, getClass() will obscure the actual class if there's a subclass that's actually invoking the method. For example, assume that in class A, method X, you call log.debug() and class B extends class A, overwriting method X, but calling super.X at some point. The log file will show class B, not class A.

Gary Kephart
Really? The logger is final and the class is passed to it at initialization, so I don't see why it would make a difference.
Michael Myers
(Not necessarily saying you're wrong, just saying I think maybe you should double-check. I don't have log4j handy, so I can't test it.)
Michael Myers
I believe that I've personally run into that before. It's been some time, though, because I gave up that particular practice after that.
Gary Kephart
+1  A: 

I would usually use the getClass() version with an instance-variable Logger (you aren't creating another logger instance, merely looking one up).

The reason for this is that in class hierarchies, it can be useful to know what the actual type is of thing you are dealing with, even if logging is occurring from within a method on the superclass.

Normally a simple textual search will give you exactly what log statement is being called anyway, so I haven't found it confusing in practice.

oxbow_lakes
+1  A: 

Other posters have already commented that getClass won't work if you want to define a static Logger - and defining one per-instance is inefficient.

If you want the correct class inferred at run time, and you are using at least Java 5, take a look at log5j, which wraps log4j in a Java 5 API.

This lets you write things like:

private static final Logger log = Logger.getLogger();

and even:

log.debug( "This thing broke: %s due to bar: %s on this thing: %s", foo, bar, car );
Bill Michell
Hmm, I thought they would have to be doing something funny with generics to allow "Logger.getLogger();". Turns out they're doing exactly what I implemented for my own project's log manager: create an Exception and read the stack trace. Still, it does make me feel that I'm doing something legal. :)
Michael Myers