Why calling LoggerFactory.getLogger(…) every time is not recommended?

前端 未结 11 2246
借酒劲吻你
借酒劲吻你 2020-12-24 01:07

I\'ve read tons of posts and documents (on this site and elsewhere) pointing that the recommended pattern for SFL4J logging is:

public class MyClass {
    fi         


        
11条回答
  •  情歌与酒
    2020-12-24 01:25

    Repeated calls to LoggerFactory.getLogger(clazz) should not result in a new Logger object each time. But that does not mean that the calls are free. While the actual behaviour depends on the logging system behind the facade, it is highly likely that each getLogger entails a lookup in a concurrent or synchronized data structure1 to look for a pre-existing instance.

    If your application makes lots of calls to your MyLoggerWrapper.debug method, this can all add up to a significant performance hit. And in a multi-threaded application, it might be a concurrency bottleneck.

    Other issues mentioned by other answers are also important:

    • Your application can no longer use logger.isDebugEnabled() to minimize the overheads when debugging is disabled.
    • The MyLoggerWrapper class obscures the class names and line numbers of your application's debug calls.
    • The code using MyLoggerWrapper will probably be more verbose if you make multiple logger calls. And the verbosity will be in the area where it impacts readability most; i.e. in the methods that do things that need logging.

    Finally, this is just "not the way that it is done".


    1 - Apparently it is a Hashtable in Logback and Log4j, and that means that the potential for a concurrency bottleneck definitely exists. Note that this is not a criticism of those logging frameworks. Rather, the getLogger method was not designed/optimized to be used this way.

提交回复
热议问题