springboot项目不重启项目修改日志级别

场景:线上某一目录下类的日志打印的日志级别低(如:DEBUG),导致线上打印大量日志。

解决方案一:

  修改spring-logback中日志级别,重新发版。

解决方案二:

  curl接口

  @RequestMapping(value = "/v1/test/log4J/level", method = RequestMethod.GET)
    public void testLog4JLevel(@RequestParam String levelStr, @RequestParam String path) {
        if (loggerContext == null) {
            if (LoggerFactory.getILoggerFactory() instanceof LoggerContext) {
                loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
            } else {
                logger.warn("无法获取loggerContext, ILoggerFactory 类型异常");
                return;
            }
        }
        Level level = Level.toLevel(levelStr, null);
        if (level == null) {
            logger.warn("传入了不支持的日志级别");
        }
        // path当前无用到,测试的当前文件的日志打印,
        logger.info("修改之前INFO级别日志打印了");
        logger.debug("修改之前DEBUG级别日志打印了");
        Level old = loggerContext.getLogger("com.json.serialize.test.controller").getLevel();
        loggerContext.getLogger("com.json.serialize.test.controller").setLevel(level);
        logger.info("{}的日志级别调整完成,原级别为{},调整为{}", "com.json.serialize.test.controller", old, level);

        logger.info("修改之后INFO级别日志打印了");
        logger.debug("修改之后DEBUG级别日志打印了");
    }

 解决方案三:

  如果使用的是Apollo,在监听器中实现日志级别调整

 

@Component 
public class LogLeveloConfigChangeListener implements ConfigChangeListener {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());



  @Override 
    public void onChange(ConfigChangeEvent changeEvent) {
    // 获取对象
   if (loggerContext == null) {
            if (LoggerFactory.getILoggerFactory() instanceof LoggerContext) {
                loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
            } else {
                logger.warn("无法获取loggerContext, ILoggerFactory 类型异常");
                return;
            }
        }

     // for (String key : changeEvent.changedKeys()) {

       Level level = Level.toLevel(change.getNewValue(), null);
                if (level == null) {
                    logger.warn("日志级别不支持");
                    continue;
                }
           
            Level old = loggerContext.getLogger(key).getLevel();
            loggerContext.getLogger(loggerName).setLevel(level);

      }
  }

}

  

 

posted @ 2021-12-10 19:11  薛小生  阅读(126)  评论(0编辑  收藏  举报