log4j2和logback动态修改日志级别工具类

丨Fanny丨Cri 2020-02-13

工作中,有些场景需要动态修改线上日志记录器的打印日志级别,

   本文的两个工具类使用的版本如下:

----------------logback---------------------

 <dependency>
   <groupId>ch.qos.logback</groupId>
   <artifactId>logback-core</artifactId>
   <version>1.1.8</version>
</dependency>
-----------------log4j2--------------------
<dependency>?
   <groupId>org.springframework.boot</groupId>?
   <artifactId>spring-boot-starter-log4j2</artifactId>?
   <version>1.5.12.RELEASE</version>?
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>2.7</version>
 </dependency>

-----------------Log4j2Controller-------------------------

@Api(tags = "Log4j2Controller",description = "Log4j2控制类")@RestController@RequestMapping("/log/control")public class Log4j2Controller {private static final Logger logger = LoggerFactory.getLogger(Log4j2Controller.class);    @RequestMapping(value = "/getLoglevel", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")public Level getLoglevel(@RequestParam(value="package") String packageName) throws Exception {//package 指定修改日志级别的包路径 ,如 org.mybatis           logger.info("getLoglevel packageName is {}",packageName);//        LoggerContext loggerContext = (LoggerContext)LoggerFactory.getILoggerFactory();           LoggerContext ctx = (LoggerContext) LogManager.getContext(false);          return  ctx.getLogger(packageName).getLevel();//        return loggerContext.getLogger(packageName).getLevel();    }@RequestMapping(value = "/setLoglevel", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")public String setLoglevel(@RequestParam("loglevel") String logLevel, @RequestParam(value="package") String packageName) throws Exception {//trace --> debug --> info --> warn --> error -->fatal//        LoggerContext ctx = (LoggerContext) LogManager.getContext(false);//        ctx.getLogger(packageName).setLevel(Level.valueOf(logLevel));//        ctx.updateLoggers();        // org。 apache.logging.log4j.core.config.Configurator;        logger.info("setLoglevel packageName is {},logLevel is {}",packageName,logLevel);        try{        Configurator.setLevel(packageName,Level.valueOf(logLevel));        }catch (Exception e){logger.error("Exception setLoglevel packageName is {},logLevel is {}",packageName,logLevel,e);            return "fail";        }return "success";    }@RequestMapping(value = "/setRootLoglevel", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")public String setRootLoglevel(@RequestParam("loglevel") String logLevel) throws Exception {logger.info("setRootLoglevel ,logLevel is {}",logLevel);        //trace --> debug --> info --> warn --> error -->fatal        try {//设置根记录器            Configurator.setRootLevel(Level.valueOf(logLevel));        }catch (Exception e){logger.error("Exception setRootLoglevel ,logLevel is {}",logLevel,e);            return  "fail";        }return "success";    }@RequestMapping(value = "/testLoglevel", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")public String testLoglevel() throws Exception {logger.debug("current log level is debug..........debug...");        logger.info("current log level is info.........info......");        logger.warn("current log level is warn.......warn.......");        logger.error("current log level is error.......error.......");        return "success";    }}-----------------LogbackController-------------------------
@Api(tags = "LogbackController",description = "logback控制类")@RestController@RequestMapping("/log/control")public class LogbackController {private static Logger logger = LoggerFactory.getLogger(LogbackController.class);    @RequestMapping(value = "/getLoglevel", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")public Level getLoglevel(@RequestParam(value="package") String packageName) throws Exception {//package 指定修改日志级别的包路径 ,如 org.mybatis        logger.info("getLoglevel packageName is {}",packageName);        LoggerContext loggerContext = (LoggerContext)LoggerFactory.getILoggerFactory();        return loggerContext.getLogger(packageName).getLevel();    }@RequestMapping(value = "/setLoglevel", method = {RequestMethod.GET, RequestMethod.POST})@ResponseBody    public String setLoglevel(@RequestParam("loglevel") String logLevel, @RequestParam(value="package") String packageName) throws Exception {//trace --> debug --> info --> warn --> error -->fatal        logger.info("setLoglevel packageName is {},logLevel is {}",packageName,logLevel);        try{        LoggerContext loggerContext =(LoggerContext)LoggerFactory.getILoggerFactory();        loggerContext.getLogger(packageName).setLevel(Level.valueOf(logLevel));        }catch (Exception e){logger.error("Exception packageName is {},logLevel is {}",packageName,logLevel,e);            return "fail";        }return "success";    }@RequestMapping(value = "/setRootLoglevel", method = {RequestMethod.GET, RequestMethod.POST})@ResponseBody    public String setRootLoglevel(@RequestParam("loglevel") String logLevel) throws Exception {//trace --> debug --> info --> warn --> error -->fatal        logger.info("setRootLoglevel ,logLevel is {}",logLevel);        try{            LoggerContext loggerContext =(LoggerContext)LoggerFactory.getILoggerFactory();            //设置全局日志级别            ch.qos.logback.classic.Logger logger=loggerContext.getLogger("root");            logger.setLevel(Level.toLevel(logLevel));        }catch (Exception e){logger.error("Exception setRootLoglevel,logLevel is {}",logLevel,e);            return "fail";        }return "success";    }@RequestMapping(value = "/testLoglevel", method = {RequestMethod.GET, RequestMethod.POST})@ResponseBody    public String testLoglevel() throws Exception {logger.debug("current log level is debug..........debug...");        logger.info("current log level is info.........info......");        logger.warn("current log level is warn.......warn.......");        logger.error("current log level is error.......error.......");        return "success";    }}备注:  1、logback和log4j2也有其它方式动态修改日志,但需要有方案或权限修改线上部署服务器的修改权限      比如logback.xml中的configuration标签有<configuration scan="true" scanPeriod="60 seconds" debug="false">这种配置,  其中的scan如果设置为true的话,项目在启动后就会默认每一分钟自动扫描配置文件,如果有改变则重新加载,而我们还可以设置自动扫描的时间间隔属性scanPeriod,可以设置成30秒或者5分钟。  现在只要在logback.xml中添加一个属性,以后可以直接在服务器上修改logback.xml中root的level属性或者直接替换整个logback.xml文件,然后过会项目的日志输出级别就会改变了,不需要再重启项目。   2、本文主要介绍代码动态修改线上日志级别
 

相关推荐