更换Spring底层日志框架

更换Spring底层日志框架

spring-jcl

在spring中有一个模块叫做spring-jcl,是Spring的日志框架,底层是会对日志框架进行判断的,是根据日志框架做优先级选取的。

spring-jcl底层日志框架加载优先级

有一个优先级:LOG4J2 级是最高的,其次是SLF4J (>=1.3)、SLF4J(<1.3)、JUL

这个加载优先级可以在一个叫LogAdapter的类中看到,所以说要更换的实现,只需导入相应的jar包即可,spring-jcl在底层会做优先级判断以确定底层日志框架的选择。

看下面源吗就知道,LogAdapter会根据项目拥有的日志框架,以更改其底层日志框架。
如果需要更换spring底层默认使用的日志框架,只需要导入相应的日志框架即可,spring-jcl将会根据优先级使用不同的日志框架。
Java常用的日志框架介绍:https://blog.csdn.net/qq_43203949/article/details/119902321

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


private static final LogApi logApi;

static {
    if (isPresent(LOG4J_SPI)) {
        if (isPresent(LOG4J_SLF4J_PROVIDER) && isPresent(SLF4J_SPI)) {
            // 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 boot的选择

spring boot默认使用logback日志框架(logback是面向slf4j接口编程的)

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-logging -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-logging</artifactId>
    <version>2.3.11.RELEASE</version>
</dependency>

如果想使用log4j2去代替logback的话,就导入下面这个jar包

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-log4j2 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
    <version>2.5.4</version>
</dependency>

posted @   鸭梨的药丸哥  阅读(8)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示