龙空技术网

Springboot生产环境下你知道如何动态修改日志级别吗?

Spring全家桶实战案例 531

前言:

如今咱们对“root用户启动tomcat后修改日志权限”都比较注重,同学们都想要分析一些“root用户启动tomcat后修改日志权限”的相关知识。那么小编在网上收集了一些对于“root用户启动tomcat后修改日志权限””的相关资讯,希望咱们能喜欢,同学们一起来学习一下吧!

环境:Springboot2.4.12

项目运行时需要打印更加详细的日志信息又不想修改配置文件然后重启服务,有没有一种办法可以不直接修改配置重启服务的方式控制日志的级别呢?有,如果你了解过Spring Boot Admin的应该都知道它提供了动态切换日志级别的功能,本篇文章将带你了解不通过Spring Boot Admin动态实现日志切换的功能。

测试Controller

package com.pack.logger.change_level@RestController@RequestMapping("/logger")public class LoggerLevelChangeController {    private static final Logger logger = LoggerFactory.getLogger(LoggerLevelChangeController.class) ;    @GetMapping("/print")  public Object print() {    logger.info("This is Info logger...") ;    logger.debug("This is Debug logger...") ;    return "print" ;  }  }

配置文件中配置对该包进行配置日志级别

logging:  level:    '[com.pack.logger.change_level]': INFO

测试

2023-01-10 16:29:59.012  INFO 66436 --- [nio-8082-exec-5] c.p.l.c.LoggerLevelChangeController      : This is Info logger...

当前对com.pack.logger.change_level该包配置的日志级别是INFO,所以这里输出了info级别的日志信息。当把级别调整为DEBUG后,控制台中会输出INFO和DEBUG的日志信息,这里修改完后我们是需要重新启动服务的。接下来看看如何不通过重启服务也能动态的调整日志的级别。

修改日志级别

接着我们在上面的Controller中添加如下方法

@GetMapping("/level")public Object changeLevel(String level) {  LoggingSystem system = LoggingSystem.get(LoggingSystem.class.getClassLoader());  // 第一个参数指定你需要设置的日志记录器的名称  // 第二个参数将通过接口传入的级别转换为LogLevel后进行设置  system.setLogLevel("com.pack.logger.change_level", resolveLogLevel(level)) ;  return "change logger level success" ;}private LogLevel resolveLogLevel(String level) {  String trimmedLevel = level.trim();  return LogLevel.valueOf(trimmedLevel.toUpperCase(Locale.ENGLISH));}

通过LogginSystem对象进行日志级别的设置。

测试

将日志级别设置为debug

再次方法上面的print接口,控制台输出:

2023-01-10 16:38:40.490  INFO 66436 --- [nio-8082-exec-9] c.p.l.c.LoggerLevelChangeController      : This is Info logger...2023-01-10 16:38:40.490 DEBUG 66436 --- [nio-8082-exec-9] c.p.l.c.LoggerLevelChangeController      : This is Debug logger...

日志级别切换成功,如果服务重启后你这动态设置的也将无效。

修改整个系统日志级别

上面的示例是仅仅对指定的日志记录器的名称进行设置,如果要对整个系统的日志级别进行调整可以通过如下方式:

// 修改上面的changeLevel方法// 将要设置的日志记录器名称也通过参数传递@GetMapping("/level")public Object changeLevel(String name, String level) {  LoggingSystem system = LoggingSystem.get(LoggingSystem.class.getClassLoader());  // 如果日志记录器名称传入的是root,那么将其设置为null  if (name.equalsIgnoreCase("root")) {    name = null;  }  // 只要将name置为null,那么整个系统的级别都将一同进行调整  system.setLogLevel(name, resolveLogLevel(level)) ;  return "change logger level success" ;}

测试:

将root日志级别修改为debug

2023-01-10 16:48:15.244 DEBUG 50544 --- [nio-8082-exec-6] o.a.coyote.http11.Http11InputBuffer      : Before fill(): parsingHeader: [true], parsingRequestLine: [true], parsingRequestLinePhase: [0], parsingRequestLineStart: [0], byteBuffer.position(): [0], byteBuffer.limit(): [0], end: [1166]2023-01-10 16:48:15.244 DEBUG 50544 --- [nio-8082-exec-6] o.a.tomcat.util.net.SocketWrapperBase    : Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@619d8bee:org.apache.tomcat.util.net.NioChannel@38066775:java.nio.channels.SocketChannel[connected local=/0:0:0:0:0:0:0:1:8082 remote=/0:0:0:0:0:0:0:1:59173]], Read from buffer: [0]2023-01-10 16:48:15.244 DEBUG 50544 --- [nio-8082-exec-6] org.apache.tomcat.util.net.NioEndpoint   : Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@619d8bee:org.apache.tomcat.util.net.NioChannel@38066775:java.nio.channels.SocketChannel[connected local=/0:0:0:0:0:0:0:1:8082 remote=/0:0:0:0:0:0:0:1:59173]], Read direct from socket: [1166]2023-01-10 16:48:15.244 DEBUG 50544 --- [nio-8082-exec-6] o.a.coyote.http11.Http11InputBuffer      : Received [GET /logger2/print HTTP/1.1Host: localhost:8082Connection: keep-aliveCache-Control: max-age=0sec-ch-ua: "Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"sec-ch-ua-mobile: ?0sec-ch-ua-platform: "Windows"Upgrade-Insecure-Requests: 1User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9Sec-Fetch-Site: noneSec-Fetch-Mode: navigateSec-Fetch-User: ?1Sec-Fetch-Dest: documentAccept-Encoding: gzip, deflate, brAccept-Language: zh-CN,zh;q=0.9Cookie: rememberMe=true; SESSION=YzQ4NTBkOTQtN2EzYi00YWNjLTk0ZmItZTBmYWVlNGJiNDUx; username=admin; size=small; sidebarStatus=1; password=KfhG4ggUsr1BSTaK5EMdiKhM+5GWwmRl9agleoPd4kaDAjpntUNu81ogBYVblALKNf9uqqnY+vEmCpY0ALWuyw==; Admin-Token=eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6Ijk0MGEwZmVhLWY2NWMtNGRmNy1hMDhhLWMxZDRhMDBkODZmOSJ9.r4syG-ZXBwOre2p6CDpIqaBePZuzPHFjako6oGXUejqxzxAoHA70Ov5bwmqJ9WB-rnwPQx-QSKxLJKDcgfBKdw; JSESSIONID=862D0514B6BDF558E299783289188AB9]2023-01-10 16:48:15.245 DEBUG 50544 --- [nio-8082-exec-6] o.a.t.util.http.Rfc6265CookieProcessor   : Cookies: Parsing b[]: rememberMe=true; SESSION=YzQ4NTBkOTQtN2EzYi00YWNjLTk0ZmItZTBmYWVlNGJiNDUx; username=admin; size=small; sidebarStatus=1; password=KfhG4ggUsr1BSTaK5EMdiKhM+5GWwmRl9agleoPd4kaDAjpntUNu81ogBYVblALKNf9uqqnY+vEmCpY0ALWuyw==; Admin-Token=eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6Ijk0MGEwZmVhLWY2NWMtNGRmNy1hMDhhLWMxZDRhMDBkODZmOSJ9.r4syG-ZXBwOre2p6CDpIqaBePZuzPHFjako6oGXUejqxzxAoHA70Ov5bwmqJ9WB-rnwPQx-QSKxLJKDcgfBKdw; JSESSIONID=862D0514B6BDF558E299783289188AB92023-01-10 16:48:15.245 DEBUG 50544 --- [nio-8082-exec-6] o.a.catalina.connector.CoyoteAdapter     :  Requested cookie session id is 862D0514B6BDF558E299783289188AB92023-01-10 16:48:15.245 DEBUG 50544 --- [nio-8082-exec-6] o.a.c.authenticator.AuthenticatorBase    : Security checking request GET /logger2/print2023-01-10 16:48:15.245 DEBUG 50544 --- [nio-8082-exec-6] org.apache.catalina.realm.RealmBase      :   No applicable constraints defined2023-01-10 16:48:15.245 DEBUG 50544 --- [nio-8082-exec-6] o.a.c.authenticator.AuthenticatorBase    : Not subject to any constraint2023-01-10 16:48:15.245 DEBUG 50544 --- [nio-8082-exec-6] org.apache.tomcat.util.http.Parameters   : Set encoding to UTF-82023-01-10 16:48:15.245 DEBUG 50544 --- [nio-8082-exec-6] o.s.web.servlet.DispatcherServlet        : GET "/logger2/print", parameters={}2023-01-10 16:48:15.246 DEBUG 50544 --- [nio-8082-exec-6] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.pack.logger.change_level.LoggerController#print()2023-01-10 16:48:15.246  INFO 50544 --- [nio-8082-exec-6] c.p.l.change_level.LoggerController      : This is Info logger...2023-01-10 16:48:15.246 ERROR 50544 --- [nio-8082-exec-6] c.p.l.change_level.LoggerController      : This is Error logger...2023-01-10 16:48:15.246 DEBUG 50544 --- [nio-8082-exec-6] m.m.a.RequestResponseBodyMethodProcessor : Using 'text/html', given [text/html, application/xhtml+xml, image/avif, image/webp, image/apng, application/xml;q=0.9, application/signed-exchange;v=b3;q=0.9, */*;q=0.8] and supported [text/plain, */*, text/plain, */*, application/json, application/*+json, application/json, application/*+json]2023-01-10 16:48:15.247 DEBUG 50544 --- [nio-8082-exec-6] m.m.a.RequestResponseBodyMethodProcessor : Writing ["print"]2023-01-10 16:48:15.247 DEBUG 50544 --- [nio-8082-exec-6] o.s.web.servlet.DispatcherServlet        : Completed 200 OK2023-01-10 16:48:15.247 DEBUG 50544 --- [nio-8082-exec-6] o.a.coyote.http11.Http11InputBuffer      : Before fill(): parsingHeader: [true], parsingRequestLine: [true], parsingRequestLinePhase: [0], parsingRequestLineStart: [0], byteBuffer.position(): [0], byteBuffer.limit(): [0], end: [1166]2023-01-10 16:48:15.247 DEBUG 50544 --- [nio-8082-exec-6] o.a.tomcat.util.net.SocketWrapperBase    : Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@619d8bee:org.apache.tomcat.util.net.NioChannel@38066775:java.nio.channels.SocketChannel[connected local=/0:0:0:0:0:0:0:1:8082 remote=/0:0:0:0:0:0:0:1:59173]], Read from buffer: [0]2023-01-10 16:48:15.247 DEBUG 50544 --- [nio-8082-exec-6] org.apache.tomcat.util.net.NioEndpoint   : Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@619d8bee:org.apache.tomcat.util.net.NioChannel@38066775:java.nio.channels.SocketChannel[connected local=/0:0:0:0:0:0:0:1:8082 remote=/0:0:0:0:0:0:0:1:59173]], Read direct from socket: [0]2023-01-10 16:48:15.247 DEBUG 50544 --- [nio-8082-exec-6] o.a.coyote.http11.Http11InputBuffer      : Received []2023-01-10 16:48:15.247 DEBUG 50544 --- [nio-8082-exec-6] o.apache.coyote.http11.Http11Processor   : Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@619d8bee:org.apache.tomcat.util.net.NioChannel@38066775:java.nio.channels.SocketChannel[connected local=/0:0:0:0:0:0:0:1:8082 remote=/0:0:0:0:0:0:0:1:59173]], Status in: [OPEN_READ], State out: [OPEN]2023-01-10 16:48:15.247 DEBUG 50544 --- [nio-8082-exec-6] org.apache.tomcat.util.net.NioEndpoint   : Registered read interest for [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@619d8bee:org.apache.tomcat.util.net.NioChannel@38066775:java.nio.channels.SocketChannel[connected local=/0:0:0:0:0:0:0:1:8082 remote=/0:0:0:0:0:0:0:1:59173]]2023-01-10 16:48:16.258 DEBUG 50544 --- [nio-8082-exec-7] o.apache.tomcat.util.threads.LimitLatch  : Counting down[http-nio-8082-exec-7] latch=22023-01-10 16:48:16.258 DEBUG 50544 --- [nio-8082-exec-7] org.apache.tomcat.util.net.NioEndpoint   : Calling [org.apache.tomcat.util.net.NioEndpoint@78b6cb49].closeSocket([org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@76712a2f:org.apache.tomcat.util.net.NioChannel@724ea039:java.nio.channels.SocketChannel[connected local=/0:0:0:0:0:0:0:1:8082 remote=/0:0:0:0:0:0:0:1:59176]])

这次输出了很多的信息,整个请求的所有信息。

关闭日志

修改上面解析日志级别的方法

private LogLevel resolveLogLevel(String level) {  String trimmedLevel = level.trim();  if ("false".equalsIgnoreCase(trimmedLevel)) {    return LogLevel.OFF;  }  return LogLevel.valueOf(trimmedLevel.toUpperCase(Locale.ENGLISH));}

只需要将level设置为false即可

完毕!!!

关注我长期更新

SpringBoot对Spring MVC都做了哪些事?(一)

SpringBoot对Spring MVC都做了哪些事?(二)

SpringBoot对Spring MVC都做了哪些事?(三)

SpringBoot对Spring MVC都做了哪些事?(四)

Spring Retry重试框架的应用

Spring MVC 异步请求方式

Spring MVC 异常处理方式

标签: #root用户启动tomcat后修改日志权限