java
复制代码
package com.dj.springtest.controller;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;
/**
* Date: 2024/1/13
* Time: 22:02
* Description: No Description
*/
@RestController
public class LogController {
private static final List<String> LEVELS = Arrays.asList("ALL", "all", "TRACE", "trace", "DEBUG", "debug", "INFO", "info", "WARN", "warn", "ERROR", "error", "OFF", "off");
/**
* 设置日志界级别
*
* @param overall 全局设置
* @param part 部分设置
* @param packagePath 涵盖包,如果有多个path,请使用英文逗号分隔
*/
@GetMapping("/log/level")
public String setLogLevel(String overall, String part, String packagePath) {
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
if (StringUtils.isNotBlank(overall) && LEVELS.contains(overall)) {
Logger rootLogger = loggerContext.getLogger("root");
rootLogger.setLevel(Level.toLevel(overall));
}
//根据包路径进行设置
if (StringUtils.isNotBlank(part) && LEVELS.contains(part) && StringUtils.isNotBlank(packagePath)) {
String[] paths = packagePath.split(",");
for (String path : paths) {
Logger pathLogger = loggerContext.getLogger(path);
pathLogger.setLevel(Level.toLevel(part));
}
}
return "Succeeded in changing the log level";
}
}