日志那些事儿——slf4j集成logback/log4j

前言

日志Logger漫谈中提到了slf4j仅仅是作为日志门面,给用户提供统一的API使用,而真正的日志系统的实现是由logback或者log4j这样的日志系统实现,那究竟slf4j是怎样集成logback或者log4j的呢?

集成logback

前文中提到,如果要使用slf4j+logback,需要引入slf4j-api及logback-classic、logback-core三个jar包。

  • 我们一般这样使用
Logger logger = LoggerFactory.getLogger("logger1");
logger.info("This is a test msg from: {}", "LNAmp");
  • LoggerFactory.getLogger的源代码如下:
public static Logger getLogger(String name) {
    ILoggerFactory iLoggerFactory = getILoggerFactory();
    return iLoggerFactory.getLogger(name);
  }

需要注意的是,Logger、LoggerFactory、ILoggerFactory都是slf4j-api.jar中的类或接口。 从源码看来,获取Logger有两个过程,现获取对应的ILoggerFactory,再通过ILoggerFactory获取Logger

public static ILoggerFactory getILoggerFactory() {
    if (INITIALIZATION_STATE == UNINITIALIZED) {
      INITIALIZATION_STATE = ONGOING_INITIALIZATION;
      performInitialization();
    }
    switch (INITIALIZATION_STATE) {
      case SUCCESSFUL_INITIALIZATION:
        return StaticLoggerBinder.getSingleton().getLoggerFactory();
      case NOP_FALLBACK_INITIALIZATION:
        return NOP_FALLBACK_FACTORY;
      case FAILED_INITIALIZATION:
        throw new IllegalStateException(UNSUCCESSFUL_INIT_MSG);
      case ONGOING_INITIALIZATION:
        // support re-entrant behavior.
        // See also http://bugzilla.slf4j.org/show_bug.cgi?id=106
        return TEMP_FACTORY;
    }
    throw new IllegalStateException("Unreachable code");
  }
  private final static void performInitialization() {
    bind();
    if (INITIALIZATION_STATE == SUCCESSFUL_INITIALIZATION) {
      versionSanityCheck();
    }
  }

  private final static void bind() {
    try {
      Set staticLoggerBinderPathSet = findPossibleStaticLoggerBinderPathSet();
      reportMultipleBindingAmbiguity(staticLoggerBinderPathSet);
      // the next line does the binding
      StaticLoggerBinder.getSingleton();
      INITIALIZATION_STATE = SUCCESSFUL_INITIALIZATION;
      reportActualBinding(staticLoggerBinderPathSet);
      emitSubstituteLoggerWarning();
    } catch (NoClassDefFoundError ncde) {
      String msg = ncde.getMessage();
      if (messageContainsOrgSlf4jImplStaticLoggerBinder(msg)) {
        INITIALIZATION_STATE = NOP_FALLBACK_INITIALIZATION;
        Util.report("Failed to load class \"org.slf4j.impl.StaticLoggerBinder\".");
        Util.report("Defaulting to no-operation (NOP) logger implementation");
        Util.report("See " + NO_STATICLOGGERBINDER_URL
                + " for further details.");
      } else {
        failedBinding(ncde);
        throw ncde;
      }
    } catch (java.lang.NoSuchMethodError nsme) {
      String msg = nsme.getMessage();
      if (msg != null && msg.indexOf("org.slf4j.impl.StaticLoggerBinder.getSingleton()") != -1) {
        INITIALIZATION_STATE = FAILED_INITIALIZATION;
        Util.report("slf4j-api 1.6.x (or later) is incompatible with this binding.");
        Util.report("Your binding is version 1.5.5 or earlier.");
        Util.report("Upgrade your binding to version 1.6.x.");
      }
      throw nsme;
    } catch (Exception e) {
      failedBinding(e);
      throw new IllegalStateException("Unexpected initialization failure", e);
    }
  }

获取ILoggerFactory的过程基本可以分为

  • performInitialization() : 完成StaticLoggerBinder的初始化
  • getLoggerFactory() :通过StaticLoggerBinder.getSingleton().getLoggerFactory()获取对应的ILoggerFactory

在整个获取Logger的过程,StaticLoggerBinder是个非常重要的类,其对象以单例的形式存在。在performInitialization过程中,slf4j会首先查找"org/slf4j/impl/StaticLoggerBinder.class"资源文件,目的是为了在存在多个org/slf4j/impl/StaticLoggerBinder.class时给开发者report警告信息,接着slf4j会使用StaticLoggerBinder.getSingleton()完成StaticLoggerBinder单例对象的初始化。

slf4j之所以能使用StaticLoggerBinder.getSingleton()是因为logback-classic和slf4j-log4j都按照slf4j的规定实现了各自的org/slf4j/impl/StaticLoggerBinder.class。那么如果系统中同时存在logback-classic和slf4j-log4j的话,slf4j选择哪一个呢,答案是随机挑选(这是由类加载器决定的,同包同名字节码文件的加载先后顺序不一定)。

StaticLoggerBinder初始化

logback的StaticLoggerBinder的初始化如下

  void init() {
    try {
      try {
        new ContextInitializer(defaultLoggerContext).autoConfig();
      } catch (JoranException je) {
        Util.report("Failed to auto configure default logger context", je);
      }
      StatusPrinter.printInCaseOfErrorsOrWarnings(defaultLoggerContext);
      contextSelectorBinder.init(defaultLoggerContext, KEY);
      initialized = true;
    } catch (Throwable t) {
      // we should never get here
      Util.report("Failed to instantiate [" + LoggerContext.class.getName()
          + "]", t);
    }
  }

其中ContextInitializer会完成配置文件例如logback.xml的文件解析和加载,特别要注意的是defaultLoggerContext是LoggerContext的实例,LoggerContext是logback对于ILoggerFactory的实现。

获取Logger

  public final Logger getLogger(final String name) {

    if (name == null) {
      throw new IllegalArgumentException("name argument cannot be null");
    }

    // if we are asking for the root logger, then let us return it without
    // wasting time
    if (Logger.ROOT_LOGGER_NAME.equalsIgnoreCase(name)) {
      return root;
    }

    int i = 0;
    Logger logger = root;
    Logger childLogger = (Logger) loggerCache.get(name);
  
    if (childLogger != null) {
      return childLogger;
    }
    String childName;
    while (true) {
      int h = Logger.getSeparatorIndexOf(name, i);
      if (h == -1) {
        childName = name;
      } else {
        childName = name.substring(0, h);
      }
      i = h + 1;
      synchronized (logger) {
        childLogger = logger.getChildByName(childName);
        if (childLogger == null) {
          childLogger = logger.createChildByName(childName);
          loggerCache.put(childName, childLogger);
          incSize();
        }
      }
      logger = childLogger;
      if (h == -1) {
        return childLogger;
      }
    }

在logback中,ILoggerFactory的实现是LoggerContext,调用LoggerContext.getLogger获取的Logger实例类型为ch.qos.logback.classic.Logger,是org.slf4j.Logger的实现类。获取Logger的过程可以分为

  • 是否是root,如果是,返回root
  • 从loggerCache缓存中获取,loggerCache中包含了配置文件中解析出来的logger信息和之前create过的logger
  • 将logger name以"."分割,获取或者创建的logger,例如com.mujin.lnamp,会创建名为com、com.mujin、com.mujin.lnamp的logger,并将其放入loggerCache然后返回com.mujin.lnamp。logger是root logger的child即logger.parent=ROOT

至此获取Logger完成,logback的Logger实现类为ch.qos.logback.classic.Logger

集成log4j

slf4j集成log4j需要引入slf4j-api、slf4j-log4j12、log4j三个Jar包,slf4j-log4j12用来起桥接作用。

获取Logger的过程和logback的过程一样,唯一不同的是StaticLoggerBinder的实现方式不一样,StaticLoggerBinder的构造方法如下

private StaticLoggerBinder() {
    loggerFactory = new Log4jLoggerFactory();
    try {
      Level level = Level.TRACE;
    } catch (NoSuchFieldError nsfe) {
      Util.report("This version of SLF4J requires log4j version 1.2.12 or later. See also http://www.slf4j.org/codes.html#log4j_version");
    }
  }

只是新建了Log4jLoggerFactory的实例,Log4jLoggerFactory是ILoggerFactory的实现类。

log4j版的StaticLoggerBinder获取logger过程如下

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;
    }
  }

思路很清晰

  • 从loggerMap中尝试取出
  • 如果logger name名为root,返回root
  • 使用LogManager.getLogger返回Log4j的Logger实现,其类型为 org.apache.log4j.Logger log4jLogger
  • 使用Log4jLoggerAdapter包装 org.apache.log4j.Logger log4jLogger,使其适配org.slf4j.Logger接口
  • 将Log4jLoggerAdapter尝试放入loggerMap缓存

那这样就有个疑问了,log4j的配置文件如何加载的呢?答案在LogManager的静态块中

static {
        Hierarchy h = new Hierarchy(new RootLogger(Level.DEBUG));
        repositorySelector = new DefaultRepositorySelector(h);
        String override = OptionConverter.getSystemProperty("log4j.defaultInitOverride", (String)null);
        if(override == null || "false".equalsIgnoreCase(override)) {
            String configurationOptionStr = OptionConverter.getSystemProperty("log4j.configuration", (String)null);
            String configuratorClassName = OptionConverter.getSystemProperty("log4j.configuratorClass", (String)null);
            URL url = null;
            if(configurationOptionStr == null) {
                url = Loader.getResource("log4j.xml");
                if(url == null) {
                    url = Loader.getResource("log4j.properties");
                }
            } else {
                try {
                    url = new URL(configurationOptionStr);
                } catch (MalformedURLException var5) {
                    url = Loader.getResource(configurationOptionStr);
                }
            }
            if(url != null) {
                LogLog.debug("Using URL [" + url + "] for automatic log4j configuration.");
                OptionConverter.selectAndConfigure(url, configuratorClassName, getLoggerRepository());
            } else {
                LogLog.debug("Could not find resource: [" + configurationOptionStr + "].");
            }
        }

以上会去加载log4j.properties或log4j.xml等配置文件,然后进行初始化

总结

slf4j通过StaticLoggerBinder链接log4j/logback,log4j/logback都提供了对应的StaticLoggerBinder实现,而对于org.slf4j.Logger接口,log4j提供的默认实现是Log4jLoggerAdapter,logback提供的实现是ch.qos.logback.classic.Logger。通过以上分析,我们可以回答两个问题了

  • 如何判断系统中使用了slf4j日志门面?
  • 可以通过Class.forName("org.slf4j.impl.StaticLoggerBinder"),如果没有抛出ClassNotFoundException说明使用了slf4j
  • 如何判断系统使用了slf4j+log4j还是slf4j+logback
  • 可以通过LogFactory.getLogger的返回类型判断,log4j实现是Log4jLoggerAdapter,logback实现是ch.qos.logback.classic.Logger

基于以上手段,我们可以做出一套适配log4j或者logback的日志记录工具类了,后续将有相关博文给出

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏服务端技术杂谈

dubbo源码学习笔记----registry

注册工厂 public interface RegistryFactory { Registry getRegistry(URL url); } ...

26340
来自专栏张善友的专栏

MSBUILD 命令行编译的时候请注意msbuild文件名称或路经中空格导致出错

在使用MSBUILD 去编译msbuild文件的时候,如果这个方案或者项目的名称或者路经中间有空格符号,需要把这个方案或者项目整个用引号引起来,否则编译的时候会...

22350
来自专栏码匠的流水账

聊聊springboot session timeout参数设置

本文主要介绍下spring boot中对session timeout参数值的设置过程。

2.6K20
来自专栏一枝花算不算浪漫

SpringBoot自定义序列化的使用方式--WebMvcConfigurationSupport

19910
来自专栏开发与安全

《dive into python3》 笔记摘录

0、In Python 2, the / operator usually meant integer division, but you could make...

28100
来自专栏技术专栏

logback日志写入kafka遇到的那些坑

这两天在学习storm实时流的时候需要将logback日志写入kafka,这期间遇到了很多坑,这里把遇到的坑和解决的问题记录一下,和大家共勉

2K30
来自专栏SpringBoot

springboot + jpa + redis + hibernate validator + 后台抽象

项目码云地址:https://gitee.com/DencyCheng/admin-api

27410
来自专栏一个会写诗的程序员的博客

13.6 SpringBoot集成Mongodb开发问题@EnableMongoRepositories路径配置13.6 SpringBoot集成Mongodb开发问题@EnableMongoRepo

Parameter 0 of constructor in com.restfeel.controller.BlogController required a ...

15020
来自专栏Hongten

悲观锁 HibernateTest.java

import org.hibernate.LockMode; import org.hibernate.Query; import org.hibernate....

11710
来自专栏一个会写诗的程序员的博客

第16章 Spring Boot + Kotlin: 下一代 Java 服务端开发

2017-11-22 11:55:17.205 INFO 14721 --- [ main] org.hibernate.Version ...

18810

扫码关注云+社区

领取腾讯云代金券