Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
change log level at runtime (logback and slf4j)
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/**
* change log level at runtime
* Created by nkcoder on 10/8/16.
*/
public class ChangeLogLevel {
private static Logger logger = LoggerFactory.getLogger(ChangeLogLevel.class);
private static String cachedLevel = "";
public static void main(String[] args) {
if (args == null || args.length != 1) {
logger.error("params error.");
return;
}
String logLevel = args[0];
Level level = Level.toLevel(logLevel.toUpperCase()); // default to Level.DEBUG
if (cachedLevel.equalsIgnoreCase(level.levelStr)) {
logger.debug("level: {} not changed", cachedLevel);
return;
}
logger.info("level will change from: {} to: {}", cachedLevel, level.levelStr);
cachedLevel = level.levelStr;
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
List<ch.qos.logback.classic.Logger> loggerList = loggerContext.getLoggerList();
loggerList.stream().forEach(tmpLogger -> tmpLogger.setLevel(level));
logger.debug("debug message");
logger.info("info message");
logger.error("error message");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.