アレについて記す

scala-logging (SLF4J) のログレベルを実行中に変更する

Posted on June 03, 2018 at 15:10 (JST)

Webアプリケーションで動的にログレベルを変える方法を試してみた。
お仕事で使ってる scala-logging での方法。

作成したコード [ play-loglevel-sample ]

Versionなど

libraryDependencies += "com.typesafe.scala-logging" %% "scala-logging" % "3.7.2"

結論

import ch.qos.logback.classic.{Level, LoggerContext}
import org.slf4j.LoggerFactory

val level = "debug"

val context: LoggerContext = LoggerFactory.getILoggerFactory.asInstanceOf[LoggerContext]
context.getLogger(this.getClass).setLevel(Level.valueOf(level))

こんな感じで任意のクラスのログレベルを変更することができる。

なお、Java+SLFJでの実装も同様に行える。 (scala-loggingはSLF4Jのwrapper)

LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
context.getLogger(targetLoggerName).setLevel(Level.valueOf(lebel));