How to change logback log level programmatically in Java?

naumcho picture naumcho · Mar 9, 2012 · Viewed 21.3k times · Source

I have some performance unit tests that create an unreasonable amount of logs that I don't really care for and are actually impacting performance. Can I somehow raise the log level in logback in the Before method for that unit test only (and restore it in After)? Or is there a better way of addressing that?

Answer

assylias picture assylias · Mar 20, 2012

This works for me:

public static void setLoggingLevel(Level level) {
    ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
    root.setLevel(level);
}

Then in your test, if you want all levels for example:

setLoggingLevel(Level.ALL);