springboot工程运行时动态改变logj4j2日志级别

springboot工程运行时动态改变logj4j2日志级别

核心代码:


    @ApiOperation("更新日志level")
    @GetMapping("/update-log")
    public JsonResult<String> updateLogLevel()
    {
        LoggerContext loggerContext = LoggerContext.getContext(false);
        LoggerConfig loggerConfig = loggerContext.getConfiguration().getRootLogger();
        Level now = loggerConfig.getLevel();
        
        // 600 -> 0
        int init = now.getStandardLevel().intLevel();
        int next = (init <= 0 ? 600 : init - 100);
        
        StandardLevel sl = StandardLevel.getStandardLevel(next);
        Level level = Level.toLevel(sl.name());
        System.out.println("TRACE(600), DEBUG(500), INFO(400), WARN(300), ERROR(200), FATAL(100), OFF(0) => " + level);
        loggerConfig.setLevel(level);
        loggerContext.updateLoggers();
        return JsonResult.success("系統当前日志级别:" + level.name());
    }

测试代码:

 /**
     * 测试日志打印
     */
    @Scheduled(fixedRate = 5000)
    public void run3()
    {
        log.trace("★★★★★★★★ {}", welcome);
        log.debug("★★★★★★★★ {}", welcome);
        log.info("★★★★★★★★ {}", welcome);
        log.warn("★★★★★★★★ {}", welcome);
        log.error("★★★★★★★★ {}", welcome);
    }

运行截图:
springboot工程运行时动态改变logj4j2日志级别_第1张图片
springboot工程运行时动态改变logj4j2日志级别_第2张图片
源码链接:https://gitee.com/00fly/effict-side/blob/master/springboot-hello/src/main/java/com/fly/hello/web/IndexController.java
-over-

你可能感兴趣的:(Spring,Java,spring,boot,java,后端)