Logback. Logging in a Maven Java Project

Last modified date

Comments: 0

Correct and consistent logging is imperative in any software project. Logback is one of the most popular and widely used logging solutions for Java projects.

This tutorial will show you how to add Logback to your Java project and setup the Maven dependencies.

Logback XML file

Create a new file called logback.xml and add the following configuration.

<configuration>
    <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
            <layout class="ch.qos.logback.contrib.json.classic.JsonLayout">
                <timestampFormat>yyyy-MM-dd'T'HH:mm:ss.SSSX</timestampFormat>
                <timestampFormatTimezoneId>Etc/UTC</timestampFormatTimezoneId>

                <jsonFormatter class="ch.qos.logback.contrib.jackson.JacksonJsonFormatter">
                    <prettyPrint>true</prettyPrint>
                </jsonFormatter>
            </layout>
        </encoder>
    </appender>

    <root level="debug">
        <appender-ref ref="stdout"/>
    </root>
</configuration>

Maven Project Structure

Maven Dependencies

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

        <!-- ch.qos.logback.contrib.jackson.JacksonJsonFormatter -->
        <dependency>
            <groupId>ch.qos.logback.contrib</groupId>
            <artifactId>logback-jackson</artifactId>
            <version>${logback.contrib.version}</version>
        </dependency>

        <!-- ch.qos.logback.contrib.json.classic.JsonLayout -->
        <dependency>
            <groupId>ch.qos.logback.contrib</groupId>
            <artifactId>logback-json-classic</artifactId>
            <version>${logback.contrib.version}</version>
        </dependency>
</dependencies>

Using The Logger

JakTech

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.