How to change root logging level programmatically for logback

slf4j log4j set log level programmatically
slf4j set log level command line
logback set log level
slf4j set log level properties
slf4j set log level configuration
java slf4j change log level at runtime
slf4j class level logging
slf4j custom log level

I have the following logback.xml file:

<configuration debug="true"> 

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

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

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(Logger.ROOT_LOGGER_NAME);
root.setLevel(Level.INFO);

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

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

sl4j and logback, You should set the package name as logger-name // Sets the package level to INFO LoggerContext loggerContext  I think you can use MDC to change logging level programmatically. The code below is an example to change logging level on current thread. This approach does not create dependency to logback implementation (SLF4J API contains MDC).

I assume you are using logback (from the configuration file).

From logback manual, I see

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

Perhaps this can help you change the value?

How to change root logging level programmatically, import org.slf4j.LoggerFactory; import ch.qos.logback.classic.Level; import ch.qos​.logback.classic.Logger; Logger root = (Logger)LoggerFactory. Stack Overflow Public questions and answers; Teams Private questions and answers for your team; Enterprise Private self-hosted questions and answers for your enterprise; Talent Hire technical talent

using logback 1.1.3 I had to do the following (Scala code):

import ch.qos.logback.classic.Logger
import org.slf4j.LoggerFactory    
...
val root: Logger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME).asInstanceOf[Logger]

How to change root logging level programmatically, I have the following logback.xml file: <configuration debug="true"> <appender name="STDOUT" class="ch.qos.logback.core. I think you can use MDC to change logging level programmatically. The code below is an example to change logging level on current thread. This approach does not create dependency to logback implementation (SLF4J API contains MDC).

I think you can use MDC to change logging level programmatically. The code below is an example to change logging level on current thread. This approach does not create dependency to logback implementation (SLF4J API contains MDC).

<configuration>
  <turboFilter class="ch.qos.logback.classic.turbo.DynamicThresholdFilter">
    <Key>LOG_LEVEL</Key>
    <DefaultThreshold>DEBUG</DefaultThreshold>
    <MDCValueLevelPair>
      <value>TRACE</value>
      <level>TRACE</level>
    </MDCValueLevelPair>
    <MDCValueLevelPair>
      <value>DEBUG</value>
      <level>DEBUG</level>
    </MDCValueLevelPair>
    <MDCValueLevelPair>
      <value>INFO</value>
      <level>INFO</level>
    </MDCValueLevelPair>
    <MDCValueLevelPair>
      <value>WARN</value>
      <level>WARN</level>
    </MDCValueLevelPair>
    <MDCValueLevelPair>
      <value>ERROR</value>
      <level>ERROR</level>
    </MDCValueLevelPair>
  </turboFilter>
  ......
</configuration>
MDC.put("LOG_LEVEL", "INFO");

Logback Change Log Level at Runtime Example, In this example, I will demonstrate how to change logger level in two name >​Mary Zheng demo for logback change level</ name > AppenderRefAction - Attaching appender named [consoleAppender] to Logger[ROOT]. Logback: Change root logger level programmatically A couple of years ago, I wrote about how it is possible to change log4j logging levels using JMX . I'm now using logback , which is intended to be the successor of log4j and provides several advantages over it.

As pointed out by others, you simply create mockAppender and then create a LoggingEvent instance which essentially listens to the logging event registered/happens inside mockAppender.

Here is how it looks like in test:

import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.Appender;

@RunWith(MockitoJUnitRunner.class)
public class TestLogEvent {

// your Logger
private Logger log = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);

// here we mock the appender
@Mock
private Appender<ILoggingEvent> mockAppender;

// Captor is generic-ised with ch.qos.logback.classic.spi.LoggingEvent
@Captor
private ArgumentCaptor<LoggingEvent> captorLoggingEvent;

/**
 * set up the test, runs before each test
 */
@Before
public void setUp() {
    log.addAppender(mockAppender);
}

/**
 * Always have this teardown otherwise we can stuff up our expectations. 
 * Besides, it's good coding practise
 */
@After
public void teardown() {
    log.detachAppender(mockAppender);
}


// Assuming this is your method
public void yourMethod() {
    log.info("hello world");
}

@Test
public void testYourLoggingEvent() {

    //invoke your method
    yourMethod();

    // now verify our logging interaction
    // essentially appending the event to mockAppender
    verify(mockAppender, times(1)).doAppend(captorLoggingEvent.capture());

    // Having a generic captor means we don't need to cast
    final LoggingEvent loggingEvent = captorLoggingEvent.getValue();

    // verify that info log level is called
    assertThat(loggingEvent.getLevel(), is(Level.INFO));

    // Check the message being logged is correct
    assertThat(loggingEvent.getFormattedMessage(), containsString("hello world"));
}
}

Solving Your Logging Problems with Logback, Log messages on the console will be displayed at level DEBUG or below, using the You can enable this behavior by setting the scan=true attribute: In previous examples, we've seen a configuration of the root logger: configure the log level programmatically, by casting to the ch.qos.logback.classic. In this article, we explored different ways of controlling the logging level at runtime. We started out using the built-in actuators functionality. After that, we used the auto-scan feature from Logback. Lastly, we learned how to use the Spring Boot Admin to monitor and change logging levels in a registered client application.

Logback: Change root logger level programmatically, Logback: Change root logger level programmatically. A couple of years ago, I wrote about how it is possible to change log4j logging levels  Logback has solid support for additional filtering, beyond just the log level, This is done with the help of filters – which determine whether a log message should be displayed or not. Simply put, a filter needs to implement the Filter class, with a single decide() method.

Chapter 3: Configuration - Logback, Logback can be configured either programmatically or with a configuration script expressed in LevelAction - root level set to DEBUG 17:44:58,812 |-INFO in  Three classes comprise the Logback architecture; Logger, Appender, and Layout. A logger is a context for log messages. This is the class that applications interact with to create log messages.

Update slf4j Log Level Programmatically – web/code, Slf4j is an API that sits on top of a logging framework, e.g. Log4j 2, Logback or java.util.logging. So If you want to change the log level, the best way to do this is via the configuration of Logger root = (Logger) LoggerFactory. The above example shows how to set the log level in our Logback configuration for tests. The root log level is set to INFO and the log level for our com.baeldung.testloglevel package is set to DEBUG.

Comments
  • It should be noted that the purpose of slf4j is to abstract away the logging framework, but that first method does away with that by referencing the logging framework directly.
  • If you do this and get a ClassCastException, it's most likely due to having multiple SLF4J bindings on the classpath. The log output will indicate this and which bindings are present to let you determine which one(s) you need to exclude.
  • Slf4j provides an API so that libraries can log application logs using whatever log framework the application developer wants. The point is that the application developer still must choose a log framework, depend on it, and configure it. Configuring the logger as dogbane has done does not violate this principle.
  • It does violate the principle. Otherwise, why use slf4j at all? Why not call the logback methods to also do logging?
  • @JohnWiseman If you want it be configured, then you have to configure it somewhere. As slf4j offers nothing in this respect, there will always be something dependent on the underlying logger. Be it a piece of code or a configuration file. +++ If it should be done programmatically as the OP requested, then you have no choice. Still, advantages remain: 1. Only a tiny part of the code depends on the concrete logger engine (and it could be written so that it may handle different implementations). 2. You can configure libraries written using other loggers, too.