James Marble
James Marble

Reputation: 883

How do you avoid repeating yourself when creating a logger?

I think the common idiom for creating instances of java.util.logging.Logger is this:

public class SomeClassName {

    private static final Logger LOG = Logger.getLogger(SomeClassName.class.getName());

}

My IDE will manage changing the line appropriately when I refactor my code (change the name of the class, for example). It still bugs me that I have to repeat the name of the class, though. What I'd really like to do is something like Logger.getLogger(getName()) or Logger.getLogger(class.getName()), but this isn't legal Java in a static initilization.

Is there a better way of getting at a logger that doesn't involve repeating myself?

Upvotes: 11

Views: 580

Answers (5)

Péter Török
Péter Török

Reputation: 116266

Issue 137 of The Java Specialists' Newsletter deals with this problem. It recommends applying a logger factory, which can detect the actual class name e.g. by generating an exception and analysing the call stack.

I personally find this worse than the original problem, but this is just my 2 cents. At any rate, technically it is interesting, so here it is:

public class LoggerFactory {
  public static Logger make() {
    Throwable t = new Throwable();
    StackTraceElement directCaller = t.getStackTrace()[1];
    return Logger.getLogger(directCaller.getClassName());
  }
}

...

public class BetterApplication {
  private final static Logger logger = LoggerFactory.make();

  ...
}

Upvotes: 10

Michał Kosmulski
Michał Kosmulski

Reputation: 10020

There is a trick to get the name of current class from a static context, I can't cite it from memory but it involved throwing an exception inside the static block and reading stack trace to get to the name of the class. However, it's quite a hack, so in practice I find repeating myself better than playing such tricks.

Upvotes: 0

adarshr
adarshr

Reputation: 62583

I create an Eclipse code template and use it each time.

enter image description here

You just have to type logger and press Ctrl + Space to activate it.

Upvotes: 8

davidfrancis
davidfrancis

Reputation: 3849

I use a plugin called log4e which is handy for logging.

http://log4e.jayefem.de/

You can use it to automatically add before/after logging for a method or a whole class.
Also you can get it to auto replace System.out.println's with logger statements.
Very handy.

Upvotes: 1

k-den
k-den

Reputation: 853

We do this:

private Logger log = Logger.getLogger(this.getClass());

Upvotes: 1

Related Questions