1

SLF4J&&Log4j

简介

依赖jar包:slf4j-api-x.x.x.jar,log4j.jar,slf4j-log4j12.jar

解析

log4j并没有实现slf4j相应的接口,所以加了一层桥接层(slf4j-log4j12.jar包里面的内容)来实现slf4jlog4j的调用
slf4j-log4j12.jar里面的代码很简单
clipboard.png
只有5个类,关键的两个类是Log4jLoggerFactoryLog4jLoggerAdapter,对应Log4jLoggerFactorygetLogger方法源码:

    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;
       }
    }
  1. Log4jLoggerFactory实现了slf4jILoggerFactory接口,调用getLogger方法获取Logger

  2. Log4jLoggerAdapter实现了slf4jLogger接口,并且实际代理了org.apache.log4j.Logger类,所以对Log4jLoggerAdapter的所有方法调用,最终调用的都是org.apache.log4j.Logger对应的方法

小结

log4j是通过slf4j-log4j12.jar桥接包来完美适配slf4j使用


iMouseWu
1.6k 声望53 粉丝

Conding with Java