Every class that wants to use java.util.logging generally needs to declare a logger like this:
public class MyClass {
private static Logger _log = Logger.getLogger(MyClass.class.getName());
}
How do you avoid this MyClass.class.getName() boilerplate code?
You don't need getName() if you're using a 1.2+ version of log4j, getLogger() accepts a Class argument. But as for the rest, there isn't any way around it if you want each class to have a static log member with its own category.
You can shorthand this a tiny bit, as getLogger is overloaded to also just take the class. Like so:
The Logger can be as fleixble or inflexible as you want it to be. You can grab a new logger for each class, as in your example above, and have a hierarchy of loggers where you can controll and turn on/off the logging by class. Or if your project is small or a prototype, etc, you could just call Logger.getRootLogger() - but you'll lose the flexibility of fine-tuning what you log and don't log. You could have a base class where the logger lives, and have everyone call that one, but again, you lose some flexibility:
Bottom line, if you want to keep the ability to fine-tune configure your logging later in the project (turn on finer level debugging for just one class), then you may have to stick with the boilerplate in every class.
I have a template set up in Eclipse so that I only have to type a portion of the declaration, and then Eclipse will auto-complete the rest for me.
So, I only have to type
logger
, hitCtrl+Space
, followed byEnter
, and Eclipse fills in the rest for me and adds the import declaration as well.This won't cut down on the amount of boilerplate code, but at least it cuts down on the amount of keystrokes.
You can reduce that and many other boilerplate codes with lombok
https://github.com/rzwitserloot/lombok
will be