Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you avoid repeating yourself when creating a logger?

Tags:

java

logging

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?

like image 521
James Marble Avatar asked Mar 30 '12 15:03

James Marble


People also ask

Why logging is important in Java?

In Java, logging is an important feature that helps developers to trace out the errors. Java is the programming language that comes with the logging approach. It provides a Logging API that was introduced in Java 1.4 version. It provides the ability to capture the log file.

How do you add a log statement in Java?

To use a different Layout with java. util. logging , set the Appender 's formatter property to the Layout of your choice. To do this in code, you can create a new Handler and use its setFormatter method, then assign the Handler to the Logger using logger.


Video Answer


1 Answers

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();

  ...
}
like image 199
Péter Török Avatar answered Oct 20 '22 14:10

Péter Török