SLF4j: Log facade abstract, slf4jfacade

Source: Internet
Author: User

SLF4j: Log facade abstract, slf4jfacade

Internal capacity:

  • Workflow for using slf4j in applications
  • Simple Example
  • ILoggerFactory instantiation Process
  • Create a Logger instance by ILoggerFactory
  • Slf4j adapter implementation
  • Custom Adapter

 

Nowadays, the log framework is emerging one after another. JDKLogger, Log4j, and Logback are the most commonly used. But now more and more frameworks, while using the log framework, will also use a facade (slf4j-api.jar ), the most convenient place to use this facade is that it provides the function of formatting strings.

 

Relationship between slf4j and other log frameworks

In the application, you can record the log directly using the slf4j-api.jar, instead of directly using a log framework in the Code (although there is a log framework to complete the final record ).

The following is the call relationship between applications, slf4j, slf4j-adapter.jar, and log framework when slf4j is used:

 

 

 

The following is a simple example:

package com.fjn.frame.slf4j;import org.slf4j.Logger;import org.slf4j.LoggerFactory;public class HelloWorld {   public static void main(String[] args) {      Logger logger = LoggerFactory.getLogger(HelloWorld.class);      logger.info("Hello World");   }}

 

LoggerFactory. getLogger (xxx) consists of two processes:

1. instantiate ILoggerFactory. This step is only performed for the first time.

2. Create a Logger instance based on the ILoggerFactory instance.

 

The two processes are described as follows:

 

ILoggerFactory instantiation Process

When using slf4j, you do not need to specify which log framework to use. You only need to specify the relevant adapter package. So how can we get the real ILoggerFactory implementation and instantiate it?

1. Search for the classloader in LogFactory"Org/slf4j/impl/StaticLoggerBinder. class"Class

 

private static String STATIC_LOGGER_BINDER_PATH = "org/slf4j/impl/StaticLoggerBinder.class";  private static void singleImplementationSanityCheck() {    try {      ClassLoader loggerFactoryClassLoader = LoggerFactory.class          .getClassLoader();      Enumeration paths;      if (loggerFactoryClassLoader == null) {        paths = ClassLoader.getSystemResources(STATIC_LOGGER_BINDER_PATH);      } else {        paths = loggerFactoryClassLoader            .getResources(STATIC_LOGGER_BINDER_PATH);      }      // use Set instead of list in order to deal with  bug #138      // LinkedHashSet appropriate here because it preserves insertion order during iteration      Set implementationSet = new LinkedHashSet();      while (paths.hasMoreElements()) {        URL path = (URL) paths.nextElement();        implementationSet.add(path);      }      if (implementationSet.size() > 1) {        Util.report("Class path contains multiple SLF4J bindings.");        Iterator iterator = implementationSet.iterator();        while(iterator.hasNext()) {          URL path = (URL) iterator.next();          Util.report("Found binding in [" + path + "]");        }        Util.report("See " + MULTIPLE_BINDINGS_URL + " for an explanation.");      }    } catch (IOException ioe) {      Util.report("Error getting resources from path", ioe);    }  }

If there are more than one, it will print:

 

2. Bind slf4j to the specified implementationThe operations in this step are usually:

1) single instantiation of StaticLoggerBinder.

2) Check the StaticLoggerBinder version, which requires a static non-final variable (this variable is not mandatory ),

StaticLoggerBinder.REQUESTED_API_VERSION

 

3. Get the ILoggerFactory instance

In general, a static ILoggerFactory impl = new XXXLoggerFactory () is returned ();

Use ILoggerFactory to create a Logger instance

 

LoggerFactory creates a Logger instance. In fact, the LogManager of the log framework creates a Logger and encapsulates it into a LoggerAdapter. For example, the implementation of Log4jLoggerFactory # getLogger (String name) in the Log4j adaptation package is as follows:

public Logger getLogger(String name) {    Logger slf4jLogger = loggerMap.get(name);    if (slf4jLogger != null) {      return slf4jLogger;    } else {      org.apache.log4j.Logger log4jLogger;      if(name.equalsIgnoreCase(Logger.ROOT_LOGGER_NAME))        log4jLogger = LogManager.getRootLogger();      else        log4jLogger = LogManager.getLogger(name);      Logger newInstance = new Log4jLoggerAdapter(log4jLogger);      Logger oldInstance = loggerMap.putIfAbsent(name, newInstance);      return oldInstance == null ? newInstance : oldInstance;    }  }

The following is a simple graph that shows the implementation of the adapter:

 

Custom log framework Adapter

In some companies, there must be their own Logger framework. If you want to use slf4j for logs, you need to write the relevant adapter package. With the understanding of the above two processes, it is easy to know how to customize the adapter.

The custom adapter must contain three components:

· StaticLoggerBinder

This class must comply with the following conventions:

1) the class name must be org. slf4j. impl. StaticLoggerBinder

2) This class must be singleton and must have the getSingleton () method.

3) Try to havePublic StaticStringREQUESTED_API_VERSIONAnd cannot be final.

4) Implement the org. slf4j. spi. LoggerFactoryBinder interface.

· LoggerFactoryImpl

This class must implement the org. slf4j. ILoggerFactory Interface

· LoggerAdapter

This class must implement the org. slf4j. Logger interface.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.