Eliminate declaration of Log variables

Thanks to Matt Raible's post on "log.debug vs. logger.debug" I learned another trick in OO Design.
It is possible to eliminate the need to initialize a log variable in each class when you insert a statement in the superclass.
Before in every class:
protected final Log logger = LogFactory.getLog(MyClass.class);

After merely in the Superclass:
protected final Log logger = LogFactory.getLog(getClass());

I often forgot to change the classname after I copied some code, so I hated thes logger declarations anyway.

Posted by Karsten at 17.08.04 14:42 | TrackBack

Karsten, your solution will provide the correct class context name for non-static methods. Just curious, what do you do if you need trace statements in static methods and yet want to know if the trace came from a base class method or a sub-class method?

Posted by: Ashish at 17.08.04 17:29

The logger is retrieved upon creation of the object, so it should work for static methods as well. But I haven't tried it yet.
Will have a look at this.

Posted by: Karsten at 17.08.04 23:45

This is how I do it as well. Two comments:

1) It won't work for static method calls - good! Every time I declare a method static it eventually comes back and burns me. Anything that discourages static helps.

2) Make the logger transient - otherwise you'll notice some fairly hefty objects if you serialize them.

Posted by: Joe Walnes at 18.08.04 09:15
Post a comment

Remember personal info?