Log4J: Strategies for creating Logger instances

后端 未结 10 605
不思量自难忘°
不思量自难忘° 2020-11-30 21:22

I decided to use Log4J logging framework for a new Java project. I am wondering what strategy should I use for creating/managing Logger instances and why?

10条回答
  •  时光取名叫无心
    2020-11-30 21:38

    • Create one logger per class.
    • If you have dependencies that require Commons Logging (quite likely) use slf4j's bridge for Commons Logging. Instantiate your loggers (per class) using the Commons Logging interface: private static final Log log = LogFactory.getLog(MyClass.class);
    • Manifest this pattern in your IDE using shortcuts. I use IDEA's live templates for this purpose.
    • Provide contextual information to threads using an NDC (thread local stack of strings) or an MDC (thread local map of String → ?).

    Examples for templates:

    private static final Log log = LogFactory.getLog($class$.class); // live template 'log'
    
    if (log.isDebugEnabled())
        log.debug(String.format("$string$", $vars$)); // live template 'ld', 'lw', 'le' ...
    

提交回复
热议问题