LogFactory

Log Factory - LogFactory

Introduction

As a logging facade, Hutool-log needs a log factory class to flexibly create log objects for compatibility with various logging frameworks.

The LogFactory class is used to create log objects flexibly through static methods. Its main functions are as follows:

  • LogFactory.get automatically identifies the introduced logging framework and creates a corresponding facade Log object. This method creates a singleton Log object for each class after the first creation, based on the passed class name. It also automatically identifies the current class and passes it as the class name to the logging framework.
  • LogFactory.createLog has a similar function to the get method. However, this method creates a new Log object each time it is called.
  • LogFactory.setCurrentLogFactory customizes the current logging facade’s log implementation class. When multiple logging frameworks are introduced, this method can be called to customize the logging framework used. Note that this method is global and should only be called once before getting the Log object.

Usage

Getting the Log object for the current class:

// It is recommended to create an immutable static class member variable
private static final Log log = LogFactory.get();

If you want to get a Log object with a custom name (like a regular Log implementation), you can use the following way to get the Log:

private static final Log log = LogFactory.get("I am a custom log name");

Custom Log Implementation

// Custom log implementation using Apache Commons Logging
LogFactory.setCurrentLogFactory(new ApacheCommonsLogFactory());

// Custom log implementation using JDK Logging
LogFactory.setCurrentLogFactory(new JdkLogFactory());

// Custom log implementation using Console Logging
LogFactory.setCurrentLogFactory(new ConsoleLogFactory());

Custom Log Factory (Custom Logging Facade Implementation)

LogFactory is an abstract class that can be inherited. To customize a logging facade, implement the createLog method (and possibly implement the Log interface to achieve the purpose of customizing the facade). Finally, set the custom LogFactory using the LogFactory.setCurrentLogFactory method to achieve a custom logging facade.

PS: The implementation of a custom logging facade can refer to the implementation in the cn.hutool.log.dialect package for custom extension. Essentially, implement the Log interface, create a Wrapper for the log implementation, and create an instance of this Log in the corresponding factory class. Additionally, the LogFactory can initialize some startup configuration parameters.