Creare log in formato JSON in Kotlin e Logback

Mattepuffo's logo
Creare log in formato JSON in Kotlin e Logback

Creare log in formato JSON in Kotlin e Logback

Logback è uno dei successori di Log4J.

Oggi vediamo come usarlo in Kotlin per creare dei log in formato JSON e visualizzarlo in console.

Se usate Maven potete installarlo così:

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.11</version>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback.contrib</groupId>
            <artifactId>logback-json-classic</artifactId>
            <version>0.1.5</version>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback.contrib</groupId>
            <artifactId>logback-jackson</artifactId>
            <version>0.1.5</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.9</version>
        </dependency>

Dopo di che create un file di configurazione chiamato logback.xml dentro al classpath (io l'ho mentro dentro alla cartella resources):

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>

    <appender name="json" class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.contrib.json.classic.JsonLayout">
            <jsonFormatter
                    class="ch.qos.logback.contrib.jackson.JacksonJsonFormatter">
                <prettyPrint>true</prettyPrint>
            </jsonFormatter>
            <timestampFormat>yyyy-MM-dd' 'HH:mm:ss.SSS</timestampFormat>
        </layout>
    </appender>

    <logger name="jsonLogger" level="TRACE">
        <appender-ref ref="json" />
    </logger>

</Configuration>

Infine il codice:

import org.slf4j.Logger
import org.slf4j.LoggerFactory

fun main(args: Array) {
    val logger: Logger = LoggerFactory.getLogger("jsonLogger")
    (logger as Logger).debug("MESSAGGIO DI DEBUG")
}

Enjoy!


Condividi su Facebook

Commentami!