动态修改日志级别 - TFdream/blog GitHub Wiki
动态修改日志级别 好处,主要是不用重启线上的项目,调整打印日志输出级别。 排查问题时,可以将日志级别调低,方便快速定位,没问题时,就级别调高,不打印 减少服务器压力。
日志五个级别是有顺序的,DEBUG < INFO < WARN < ERROR < FATAL,分别用来指定这条日志信息的重要程度。
- slf4j + logback组合
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
//获取应用中的所有logger实例
List<ch.qos.logback.classic.Logger> loggerList = loggerContext.getLoggerList();
//遍历更改每个logger实例的级别
for (ch.qos.logback.classic.Logger logger:loggerList){
logger.setLevel(newLevel);
}
2.slf4j + log4j
Enumeration enumeration = LogManager.getCurrentLoggers();
while (enumeration.hasMoreElements()){
org.apache.log4j.Logger logger = (org.apache.log4j.Logger) enumeration.nextElement();
logger.setLevel(org.apache.log4j.Level.ERROR);
}
3.slf4j + log4j2
public void adjustLogLevel() {
Collection<Logger> notCurrentLoggerCollection = org.apache.logging.log4j.core.LoggerContext.getContext(false).getLoggers();
Collection<org.apache.logging.log4j.core.Logger> currentLoggerCollection = org.apache.logging.log4j.core.LoggerContext.getContext().getLoggers();
Collection<org.apache.logging.log4j.core.Logger> loggerCollection = new ArrayList<>(notCurrentLoggerCollection);
loggerCollection.addAll(currentLoggerCollection);
for (org.apache.logging.log4j.core.Logger logger:loggerCollection){
logger.setLevel(org.apache.logging.log4j.Level.ERROR);
}
}