Friday, December 29, 2006

Declaring Your Logger - No Problem

I used to like the java specialists newsletter, most news used to be a bit challenging. Nowadays however the quality is lower. In the latest news, the author proposes to use the StackTrace to get the class name, in order to declare a Logger independently of any explicit reference to the class name.

While this is a clever hack, it still requires some code to be duplicated in every class, compared to Aspect/IoC approach. But was there really a problem with declaring loggers the usual way in the first place?

With modern IDEs, most people just create a template for the logger declaration line. Also, renaming MyClass to MyClass2 will rename MyClass.class to MyClass2.class automatically. Here is my template for Eclipse to which I assigned the short name log4j:

private static final Logger LOG = Logger.getLogger(${enclosing_type}.class);


2 comments :

  1. I don't bother declaring a logger anywhere, I just use IoC via a hand-rolled 'framework'.

    context.getLogger().fine("whatever");

    I don't currently need to be able to have different settings for my logger for different classes, but if I did, I think I'd change that requirement slightly, and have different settings for different categories, resulting in:

    context.getLogger(GUI).fine("the GUI is working well");

    context.getLogger(IO).fine("Just wrote something to disk");

    etc., where GUI and IO are simple enum constants.

    I don't think that auto-generating code is the best solution in many cases; it shows that something is wrong with the idiom or the language.

    ReplyDelete
  2. Hi people,

    What Heinz proposes in the latest JSN is something that could be enforced by the logging framework instead of the IDE or (as Rick) coding conventions. I see it more as a message to Ceki Gülcü et al, than for final users.

    Cheers!

    ReplyDelete