oshai/kotlin-logging

[4.0.0-beta-23] Is it currently possible to change the log level on JVM?

leinardi opened this issue · 3 comments

I am working on a pure JVM project (no Android) and I want to change the log level of slf4j programmatically. I followed the readme instructions and added the org.slf4j:slf4j-simple dependency, which enabled me to see the logs, but it does not seem to support dynamic log level changes. Is there any other slf4j implementation that allows me to do that? I am not tied to slf4j-simple, it was just the recommended one.

In short, is there any way to use this library in a JVM project together with dynamic log level support?

Thank you for reporting an issue. See the wiki for documentation and slack for questions.

oshai commented

slf4j-simple is simple. you can pick other libs such as log4j2 that has dynamic reloading of config file: https://stackoverflow.com/a/16216956/411965

I see, thank you for the input. I'm an Android developer and I always and only used logcat so I'm not familiar with all these JVM logging libraries.

After some googling I managed to get what I wanted: custom log lever, message pattern and colors on stdout
image

If anyone is interested in the code, this is what I came up with:

    val builder = ConfigurationBuilderFactory.newConfigurationBuilder()
    val console = builder.newAppender("Stdout", "CONSOLE")
        .addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT)
    console.add(
        builder.newLayout("PatternLayout")
            .addAttribute(
                "pattern",
                "%highlight{%-5level: [%t] %msg%n%throwable}" +
                    "{FATAL=bright_red, ERROR=bright_red, WARN=bright_yellow, " +
                    "INFO=bright_green, DEBUG=bright_white, TRACE=white}",
            ),
    )
    builder.add(console)
    builder.add(builder.newRootLogger(Level.TRACE).add(builder.newAppenderRef("Stdout")))
    Configurator.initialize(builder.build())
    val logger = KotlinLogging.logger {}
    logger.trace("lorem ipsum")
    logger.debug("lorem ipsum")
    logger.info("lorem ipsum")
    logger.warn("lorem ipsum")
    logger.error("lorem ipsum")

These are the Gradle dependencies:

    implementation("org.apache.logging.log4j:log4j-api:2.20.0")
    implementation("org.apache.logging.log4j:log4j-core:2.20.0")
    implementation("org.apache.logging.log4j:log4j-slf4j-impl:2.20.0")