spring boot实现动态修改日志级别——笔记

pom.xml

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-actuatorartifactId>
    <version>2.3.4.RELEASEversion>
dependency>
application.yml
management:
  endpoints:
    web:
      exposure:
        include: loggers
  endpoint:
    loggers:
      enabled: true
controller
private final Logger log = LoggerFactory.getLogger(SysLogController.class);

	@ApiOperation("查看日志级别")
	@GetMapping()
	public Result<?> log() {
		log.trace("TRACE");
		log.debug("DEBUG");
		log.info("INFO");
		log.warn("WARN");
		log.error("ERROR");
		LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
		List<ch.qos.logback.classic.Logger> loggerList = loggerContext.getLoggerList();
		//取0为ROOT级别的日志,通过/actuator/loggers修改后list的第一个下标一定和其他级别的日志一样
		return Result.ok(loggerList.get(0).getEffectiveLevel());
	}
	@ApiOperation(value = "日志级别控制",notes = "effectiveLevel必传,可选参数:TRACE,DEBUG,INFO,WARN,ERROR")
	@PostMapping("/actuator/loggers")
	public Result<?> loggers(@RequestBody JSONObject jsonObject){
		String effectiveLevel = jsonObject.getString("effectiveLevel");
		try {
			LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
			List<ch.qos.logback.classic.Logger> loggerList = loggerContext.getLoggerList();

			for (ch.qos.logback.classic.Logger loggerInstance : loggerList) {
				Level newLevel = Level.toLevel(effectiveLevel);
				loggerInstance.setLevel(newLevel);
			}
			return Result.ok();
		} catch (Exception e) {
			return Result.error(e.getMessage());
		}
	}

你可能感兴趣的:(笔记,spring,boot,maven,spring)