1

SLF4J&&Logback

简介

常用的日志主流框架基本上是基于slf4j搭配logback来实现日志输出
依赖jar包:slf4j-api-x.x.x.jar,logback-classic-x.x.x.jar,logback-core-x.x.x.jar

解析

我们获取日志实体代码:
Logger log = LoggerFactory.getLogger("test");

具体获取日志实体源码:


public static Logger getLogger(String name) {
   ILoggerFactory iLoggerFactory = getILoggerFactory();
   return iLoggerFactory.getLogger(name);
}

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:
       return TEMP_FACTORY;
    }
    throw new IllegalStateException("Unreachable code");
}

这里类StaticLoggerBinder 就必须在logback-classic-x.x.x.jar中声明,并且通过调用StaticLoggerBinder.getSingleton().getLoggerFactory()获取一个实现了ILoggerFactory的实例
(这里获取单例是通过饿汉式,依赖StaticLoggerBinder实体改成依赖一个接口是否更加优雅,然后通过SPI的方式来获取不同包里面的的不同实现)

    public interface ILoggerFactory {
        public Logger getLogger(String name);
    }

获取一个实现了Logger接口的实例,具体接口的实现是在logback-classic-x.x.x.jar中,结合logback-core-x.x.x.jar包括了所有的日志输出的细节

小结

logback是通过直接实现接口来搭配slf4j使用


iMouseWu
1.6k 声望53 粉丝

Conding with Java