Java – what are the benefits of having multiple logger instances instead of just one static logger class?

So I checked the best practices on logging in Java (slf4j, log4j, logback, etc.), and it seems that the appearance of logging API has been agreed between libraries The suggestion I've been reading is that you create a logger in each class:

class Foo{
  Logger logger = Logger.getLogger(Foo.class);
  //...
  logger.info("my log message");
  //...
}

Now I don't really get the benefit of assigning recorders to different categories Why is it that the methods in the info / debug / etc. logger class are not static?

Please don't give benefits like "you can configure your recorder according to categories. For example, you can set the log level of each class to debug...", because I think this is what you can do Complete a completely static logger class

If you look around (for example, here in stackoverflow: log4j: strategies for creating logger instances), you will find that people use this idiom:

Logger.getLogger(Thread.currentThread().getStackTrace()[2].getClass().getCanonicalName());

Now you can call the above code in the static (for example) info () method instead of creating a logger for each class, where you can identify the invocation class and apply all logger configurations equally.

So can someone tell me the real reason why someone should use a logger per class instead of a static logger? Is this purely historical? Did I miss anything? I know it may have an impact on performance, but in terms of memory usage, it is actually positive (and of course negative at runtime)

Update I think you can even use this code in static information / debugging / etc Method is more beautiful and efficient than the above code:

Reflection.getCallerClass()

However, support for this approach seems problematic > = JDK7

Solution

Calling this line in the static info () method will adversely affect the performance, because every time you need to create the entire stack trace, that is, very slow.

Assigning a logger instance to a static variable of each class means that you can explicitly represent the class, or you can use expensive methods to determine the class name only from the stack trace when loading the class You can then reuse the same logger without having to resolve the calling class again

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>