overview

Origin

To be precise, Hutool-log is just a universal facade for logging, similar to Slf4j. Since facade frameworks like Slf4j are already well-developed, why create another facade? Below, I list some problems encountered in practice:

Problems with Existing Facades

  1. Complex log object creation

Many times, we have to write a line of code to add logging to a class, and we also have to manually change the class name XXX:

private static final Logger log = LoggerFactory.getLogger(XXX.class);
  1. Methods with Exception parameters do not support variables.

My favorite form in Slf4j, which not only eliminates the cumbersome isInfoEnabled() judgment but also avoids string concatenation:

log.info("I changed the {} variable in XXX", "name");

However, in this case, the variable pattern cannot be used:

log.error("Error message", e);

Features

  1. The Logfactory.get method is no longer required (or necessary) to pass in the current class name, and it will automatically parse the current class name.
  2. The log.xxx method supports template syntax when passing in an Exception.
  3. It does not require a bridge package and automatically adapts to the introduced logging framework, and can still perfectly adapt to JDK Logging without a logging framework.
  4. In the case of introducing multiple logging frameworks, you can customize the output of the logging framework.

Principle

Hutool-log adopts a dynamic automatic adaptation mode, which automatically detects the introduced logging framework package to output logs to this framework. For example, if we introduce the Log4j package in the project, Hutool-log will automatically detect the existence of this package and output the logs to log4j. If no logging framework is introduced, the logs will be output to JDK Logging.

Therefore, Hutool-log does not have a unified configuration file. If you introduce any logging framework, you can use the configuration file of this framework.

The order in which Hutool-log detects logging frameworks is: Slf4j(Logback) > Log4j > Log4j2 > Apache Commons Logging > JDK Logging > Console

Of course, if only the Slf4j-API is introduced without any implementation, Slf4j will be skipped.

Please refer to LogFactory.create for the core code related to log framework detection.

Usage

Conventional Usage

The usage of Hutool-log is no different from that of general logging frameworks. You can simply call LogFactory.get() to get a Log implementation object.

Log log = LogFactory.get();

log.debug("This is {} log", Level.DEBUG);
log.info("This is {} log", Level.INFO);
log.warn("This is {} log", Level.WARN);

Exception e = new Exception("test Exception");
log.error(e, "This is {} log", Level.ERROR);

Usually, we need to define logs in the class as private static final Log log = LogFactory.get(); for better performance.