Integration of log4j and slf4j

1 The relationship between log4j and slf4j
can be seen in almost every jar package of log4j. In multiple sub-engineering projects, conflicts related to slf4j pop up from time to time to make you uncomfortable, so slf4j-api, slf4j-log4j12 also What is the relationship with log4j?
   
slf4j: Simple Logging Facade for Java, a simple logging facade for java. Facade facade, at a lower level, is the interface. It allows users to access different log systems through slf4j in the project according to their own preferences. More intuitively, slf4j is a data line, one end is embedded in the program, and the other end is linked to the log system, so that the information in the program can be imported into the log system and recorded.

Therefore, the slf4j entry is a collection of many interfaces. It is not responsible for the specific log implementation. It is only responsible for finding a suitable log system for binding at compile time. The specific interfaces are all defined in slf4j-api. Looking at the slf4j-api source code, you can find that except for the public final class LoggerFactory class, all are interface definitions. Therefore, slf4j-api is essentially an interface definition.

The following figure clearly describes the relationship between them. An example is the calling relationship when the system uses log4j as the log framework:
① First, the system includes slf4j-api as the interface for log access. When compiling, the private final static void bind() method in the public final class LoggerFactor class in slf4j-api will look for a specific log implementation class binding, which is mainly called by the statement StaticLoggerBinder.getSingleton().




②slf4j-log4j12 is an adapter between slf4j-api and log4j. It implements the StaticLoggerBinder interface in slf4j-api, so that the getSingleton() method of slf4j-log4j12 is bound at compile time.
③ log4j is a specific log system. Initialize Log4j through slf4j-log4j12 to achieve the final log output.

2 Implementation

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyTest3 {
	
	private static Logger log = LoggerFactory.getLogger(MyTest3.class.getName());

	public static void main(String[] args) {
		log.info("Hello");  
        log.debug("I am debug");  
        log.error("wrong");  
        log.trace("What is this");
	}
	
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327028179&siteId=291194637