Explain Codes LogoExplain Codes Logo

How to change root logging level programmatically for Logback

java
logging
logback
configuration
Anton ShumikhinbyAnton Shumikhin·Jan 4, 2025
TLDR

Switch logging levels in Logback as if you're flipping switches on a late-night coding spree! 👨‍💻💡

// Set root logger level to save your sanity (e.g., Level.INFO) ((LoggerContext) LoggerFactory.getILoggerFactory()) .getLogger(Logger.ROOT_LOGGER_NAME).setLevel(Level.INFO);

Swap Level.INFO for your desired log levelLevel.DEBUG if you're into mysteries or Level.ERROR if you like the thrill. This code snippet is the golden key 🔑 to configure the root log level in Logback.

Mini-glossary

  • LoggerContext: The underworld 🕳️ of all your logging contexts.
  • LoggerFactory: The factory 🏭 where all your loggers are crafted.
  • Logger.ROOT_LOGGER_NAME: Universal broadcaster 📢—everyone hears if you yell here.
  • setLevel(Level.INFO): Leveling up the logger to your current need.

Deep dive into log level manipulation

Direct modifications to the logging Gatekeeper

When a specific event occurs in your app and it requires you to be extra alert, updating the log level is as easy as changing your clothes.👕👖

Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); // Find your ROOT_LOGGER rootLogger.setLevel(Level.WARN); // Whisper, yells are so 2020!

Embracing real-time configurations

Configure Logback to conduct periodic scans of your config file, a habit even your dentist would be proud of: 🦷😁

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

Switching log level gears based on application events

if (alienInvasionDetected()) { // 👽 When the extraordinary happens rootLogger.setLevel(Level.ERROR); // Shine the Bat-Signal 🦇💡 }

Discover advanced logging techniques

Context-centric logging with MDC

Be like Spiderman🕷️, act locally while thinking globally.

MDC.put("userId", "PeterParker");

Testing - because we are all humans

Favorite activity of developers after coding: testing loggers! And a way to verify we get what we expect with mockAppender.

rootLogger.addAppender(mockAppender); // Logs emitted will now be caught by the mockAppender. Sneaky, isn't it? 🕵️‍♂️ rootLogger.detachAppender(mockAppender); // Always remember to clean up your mess

Scala and Logger setting - a perfect blend

For you Scala folks out there, this one's for you. Here's how you can elegantly set the logging level:

import org.slf4j.LoggerFactory import ch.qos.logback.classic.{Level, Logger} object LoggerConfigurer { def setRootLevel(level: Level): Unit = { val rootLogger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME).asInstanceOf[Logger] rootLogger.setLevel(level) // Fancy, isn't it? 🎩 } }