springboot中动态修改log4j2日志级别

springboot中动态修改log4j2日志级别

在spring boot中使用log4j2日志时,项目运行中,想要修改日志级别。

1.pom.xml依赖:

<dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.7</version>
        </dependency>

2.Log4j2Controller

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Log4j2Controller {


    private Logger log = LogManager.getFormatterLogger(Log4j2Controller.class.getName());
    @RequestMapping(value = "/log4j2")
    public String logback(){
        log.error("我是error");
        log.warn("我是warn");
        log.info("我是info");
        log.debug("我是debug");
        return "success";
    }

    /**
     * LOG4j2动态修改包名的日志级别
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/levelb")
    public String updateLogbackLevelj( @RequestParam(value="level") String level) throws Exception {
        String msg = "success";
        level = level.toLowerCase();
        org.apache.logging.log4j.core.LoggerContext ctx = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);
        Configuration config = ctx.getConfiguration();
        LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
       switch (level) {
           case "trace":
               loggerConfig.setLevel(org.apache.logging.log4j.Level.TRACE);
               break;
           case "debug":
               loggerConfig.setLevel(org.apache.logging.log4j.Level.DEBUG);
               break;
           case "info":
               loggerConfig.setLevel(org.apache.logging.log4j.Level.INFO);
               break;
           case "warn":
               loggerConfig.setLevel(org.apache.logging.log4j.Level.WARN);
               break;
           case "error":
               loggerConfig.setLevel(org.apache.logging.log4j.Level.ERROR);
               break;
           default:
               msg = "日志级别修改失败!";
               break;
       }
        ctx.updateLoggers();
        return msg;
    }

}

3.直接调用

/levelb接口即可修改日志级别。
posted @ 2018-08-13 20:33  何其小静  阅读(6102)  评论(0编辑  收藏  举报