How to change root logging level programmatically for logback

Tags: , ,

I have the following logback.xml file:

<configuration debug="true"> 

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> 
  <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>

<root level="debug">
  <appender-ref ref="STDOUT" />

Now, upon the occurrence of a specific event, I want to programmatically change the level of the root logger from debug to error. I can’t use variable substitution, it is mandatory that I do this within the code.

How can it be done ? Thanks.


Try this:

import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;

Logger root = (Logger)LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);

Note that you can also tell logback to periodically scan your config file like this:

<configuration scan="true" scanPeriod="30 seconds" > 

Source: stackoverflow