提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
在线上环境,有时候为了排查线上问题,需要动态的调整日志级别,比如调低某些类的日志级别,打印更多的有用日志信息,方便问题的排查。对于Log4j2,动态调整日志级别有两种方式,我们看下。
一、JMX方式
Log4j2官方提供了对JMX的支持,可以很方便的进行配置的修改。
具体参考官网Log4j – JMX,这里就不详细说了。
二、编程方式(推荐)
代码如下(示例):
这里推荐编程的方式,通过调用HTTP接口,实现具体Logger的级别的调整。
主要通过Configurator类的setLevel和setRootLevel方法进行设置。
// org.apache.logging.log4j.core.config.Configurator;
Configurator.setLevel("com.example.Foo", Level.DEBUG);
// You can also set the root logger:
Configurator.setRootLevel(Level.DEBUG);
具体的Controller实现类如下:
@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 ctx = (LoggerContext) LogManager.getContext(false);
return ctx.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 {
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);
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";
}
}
总结
为了排查线上问题需要动态的调整日志级别,比如调低某些类的日志级别,打印更多的有用日志信息,方便问题的排查。对于Log4j2,动态调整日志级别有JMX和编程两种方式,推荐使用编程的方式,更灵活方便。