Spring日志引用原理

常见的日志框架有LOG4J、LOG4J2、LOGBACK、JUL等等
日志门面接口:JCL、SLF4j

slf4j绑定器与桥接器大白话总结

绑定器:假如将log4j绑定到slf4j门面,那么通过slf4j实例化的日志对象就是这个绑定的日志
桥接器:假如此时slf4j绑定的是logback日志,log4j桥接到slf4j上,那么之前通过log4j实例的日志对象会被桥接到logback上,即会统一到logback上

1. spring4中日志调用原理

private static final String[] classesToDiscover = new String[]{"org.apache.commons.logging.impl.Log4JLogger",
                                                               "org.apache.commons.logging.impl.Jdk14Logger", 
                                                               "org.apache.commons.logging.impl.Jdk13LumberjackLogger",
                                                               "org.apache.commons.logging.impl.SimpleLog"};

spring4中,jcl中选用日志是依靠写死的数组,按顺序遍历实例化对应日志,所以优先log4j,没有log4j的话则用jul

spring4中如果想使用logback日志,只需要加入log4j到slf4J的桥接器即可

2.spring5日志调用原理

spring5中,对spring的jcl日志接口进行了改良

	private static final String LOG4J_SPI = "org.apache.logging.log4j.spi.ExtendedLogger";

	private static final String LOG4J_SLF4J_PROVIDER = "org.apache.logging.slf4j.SLF4JProvider";

	private static final String SLF4J_SPI = "org.slf4j.spi.LocationAwareLogger";

	private static final String SLF4J_API = "org.slf4j.Logger";

    if (isPresent(LOG4J_SPI)) {
        if (isPresent(LOG4J_SLF4J_PROVIDER) && isPresent(SLF4J_SPI)) {
            //有log4j桥接器和slf4j
            // log4j-to-slf4j bridge -> we'll rather go with the SLF4J SPI;
            // however, we still prefer Log4j over the plain SLF4J API since
            // the latter does not have location awareness support.
            logApi = LogApi.SLF4J_LAL;
        }
        else {
            // Use Log4j 2.x directly, including location awareness support
            logApi = LogApi.LOG4J;
        }
    }
    else if (isPresent(SLF4J_SPI)) {
        // Full SLF4J SPI including location awareness support
        logApi = LogApi.SLF4J_LAL;
    }
    else if (isPresent(SLF4J_API)) {
        // Minimal SLF4J API without location awareness support
        logApi = LogApi.SLF4J;
    }
    else {
        // java.util.logging as default
        logApi = LogApi.JUL;
    }



Spring日志引用原理_第1张图片

3.spring boot中日志原理

Spring日志引用原理_第2张图片


springboot中加了slf4j,logback,logback绑定器,jul桥接器,log4j2桥接器

mybatis中默认优先slf4j
tomcat中优先jul日志

所以项目统一成了logback日志

你可能感兴趣的:(Spring,java,spring,slf4j,log4j,logback,log4j2)