Creare log in formato JSON in Java e Logback

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

Creare log in formato JSON in Java e Logback

Logback è uno dei successori di Log4J.

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

Se usate Maven potete installarlo così:

    <dependencies>
        <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>
    </dependencies>

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;

public class Main {

    public static void main(String[] args) {
        Logger logger = LoggerFactory.getLogger("jsonLogger");
        ((Logger) logger).debug("MESSAGGIO DI DEBUG");
    }

}

Enjoy!


Condividi

Commentami!