How do you reduce Java logging boilerplate code?

2019-03-11 03:10发布

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?

标签: java logging
10条回答
混吃等死
2楼-- · 2019-03-11 03:27

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.

查看更多
相关推荐>>
3楼-- · 2019-03-11 03:29

You can shorthand this a tiny bit, as getLogger is overloaded to also just take the class. Like so:

public class MyClass {
    private static Logger _log = Logger.getLogger(MyClass.class);
}

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:

public class MyBase {
     protected static Logger _log = Logger.getLogger(MyClass.class);
}

public class MyClass extends MyBase {
    ....
    _log.info("Stuff....");
}

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.

查看更多
疯言疯语
4楼-- · 2019-03-11 03:35

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.

${:import(org.apache.log4j.Logger)}
private final static Logger log = Logger.getLogger(${enclosing_type}.class);
${cursor}

So, I only have to type logger, hit Ctrl+Space, followed by Enter, 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.

查看更多
SAY GOODBYE
5楼-- · 2019-03-11 03:39

You can reduce that and many other boilerplate codes with lombok

https://github.com/rzwitserloot/lombok

 @Slf4j
     public class LogExample {
 }

will be

 public class LogExample {
     private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExample.class);
 }
查看更多
登录 后发表回答