logback日志级别动态切换的四种方案

生产环境中经常有需要动态修改日志级别。
现在就介绍集中方案

方案一:开启logback的自动扫描更新

配置如下

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
    <!-- configuration标签 scan属性代表logback框架会定时检测改配置文件是否有发生改动,如果有则更新为最新配置-->

然后就将修改的配置文件拷贝到app.jar的同级目录下config/logback.xml

方案二:自定义api

代码如下

/**
 * log api
 * @author lipeng
 */
@RequestMapping("/api/log")
@RestController
public class LogbackController {

    private Logger log = LoggerFactory.getLogger(LogbackController.class);

    /**
     * logback动态修改包名的日志级别
     * @param level 日志级别
     * @param packageName 包名
     * @return 当前的日志级别
     * @throws Exception
     */
    @RequestMapping(value = "/setlevel")
    public String updateLogbackLevel( @RequestParam(value="level") String level,
                                      @RequestParam(value="packageName",defaultValue = "-1") String packageName) throws Exception {
        ch.qos.logback.classic.LoggerContext loggerContext =(ch.qos.logback.classic.LoggerContext) LoggerFactory.getILoggerFactory();
       Logger logger= null
        if(packageName.equals("-1")) {
            // 默认值-1,更改全局日志级别;否则按传递的包名或类名修改日志级别。
          logger=  loggerContext.getLogger("root")
        } else {
           logger= loggerContext.getLogger(packageName)
        }
        logger.setLevel(ch.qos.logback.classic.Level.toLevel(level));
        return logger.getLevel();
    }

}

方案三:springboot引入Actuator

1、pom.xml增加相关依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
 
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

1、配置文件中增加配置
如果是springboot1.X,

management.security.enabled=false

如果是springboot2.X,则参考如下配置

management:
  endpoint:
    health:
      show-details: "ALWAYS"
  endpoints:
    web:
      exposure:
        include: "*"

3、查看级别
我们可以发送GET 请求到 http://localhost:8080/actuator/loggers 来获取支持的日志等级,以及系统(ROOT)默认的日志等和各个包路径(com.xxx.aa等)对应的日志级别。
访问会返回所有的类的日志级别信息。
4、修改日志级别
通过 http://localhost:8080/actuator/loggers 端点提供的 POST 请求,修改包路径com.xxx.aa的日志级别为DEBUG:

发送POST 请求到 http://localhost:8080/actuator/loggers/com.xxx.aa,其中请求 Body 的内容如下:

{
"configuredLevel": "DEBUG"
}

再用GET 访问 http://localhost:8080/loggers/com.xxx.aa查看当前的日志级别:


{
configuredLevel: "DEBUG",
effectiveLevel: "INFO"
}

方案四 集成springcloudadmin来动态修改配置

springcloudadmin安装部署我就不做描述了,网上很多。
1、引入admin依赖

		<dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-client</artifactId>
        </dependency>
        <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>

2、登录springcloudadmin,找到指定的服务中某一个节点
在这里插入图片描述
然后点击左边日期,进入控制台,如下
在这里插入图片描述
这样就能动态修改了,操作比较方便。

总结

在条件允许的情况下建议使用方案四

发布了221 篇原创文章 · 获赞 9 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/lp19861126/article/details/104103348
今日推荐