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?
Have a look at using point cuts in your code
I have not looked back since using them with spring.
Here is an article on using AspectJ
http://www.developer.com/java/other/article.php/3109831
If you go for package-level loggers, with the addition of a boilerplate class per package, you can write:
There are hacks to read the class name of the caller (in fact the logging implementation has a hack to detect the current method), but I wouldn't recommend that.
Depending on your logging needs, you could create a "LoggingService" class with static methods for logging to various "channels". I have found that I really don't need logging granularity down to the class level. You can name your loggers what every works best for you. We have been using this in large, enterprise applications for several years and the granularity has really not been an issue for us.
The logging service initialized in a static initializer block...so to log a message:
LoggingService.logError("blah");
No boilerplate code in each class.
Here is an example logging service:
}
Take a look at SLF4J
Actually, the common practice of using class names for logger names is lazy more than anything.
The much better practice is to name loggers by the task context. This involves somewhat more thought process and planning but in the end, the result is much more meanigful granularity, where you can toggle logging levels for actual tasks rather than classes.
If you make the logger nonstatic, you can at least inherit it:
That's how I've always done it.