Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 7, 2023 16:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/db5ffda9b6d14e43373df9816ae5d61b to your computer and use it in GitHub Desktop.
Save dacr/db5ffda9b6d14e43373df9816ae5d61b to your computer and use it in GitHub Desktop.
logging tips with log4j2 and slf4j / published by https://github.com/dacr/code-examples-manager #44be33f5-2c29-469c-9cc6-02d74a2e1ea8/505973193ee2ab4097ae7c97ad58386ba305f4c5
// summary : logging tips with log4j2 and slf4j
// keywords : logging, tips, cheatsheet, slf4j, log4j2, @testable
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : 44be33f5-2c29-469c-9cc6-02d74a2e1ea8
// created-on : 2020-10-28T20:43:15Z
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "3.2.2"
//> using dep "org.apache.logging.log4j:log4j-api:2.20.0"
//> using dep "org.apache.logging.log4j:log4j-core:2.20.0"
//> using dep "org.apache.logging.log4j:log4j-slf4j-impl:2.20.0"
// ---------------------
import org.slf4j.{Logger, LoggerFactory}
import org.apache.logging.log4j.{LogManager,Level}
import org.apache.logging.log4j.core.LoggerContext
import java.lang.invoke.MethodHandles
import org.slf4j.LoggerFactory
println("A way to change log4j2 configuration programmatically Through the LoggerContext")
val context = LogManager.getContext(false).asInstanceOf[LoggerContext]
val config = context.getConfiguration()
val rootConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME)
rootConfig.setLevel(Level.DEBUG)
context.updateLoggers()
object LoggingTips {
val logger = LoggerFactory.getLogger(MethodHandles.lookup.lookupClass)
logger.info("Thanks to MethodHandles, the classname is found automatically !")
def go():Unit = {
logger.info("GO {}", 42L)
}
}
LoggingTips.go()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment