Logback Logging Example

In this article, you will see very basic logging using Logback.

First create a new Java Project and configure it as Maven Project. For Reference, Click Here

Add the following dependencies in pom.xml

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

1. Logback Configuration

The following configuration generates simple logs on console.

logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level  %logger{35} - %msg%n</pattern>
        </encoder>
    </appender>
     
    <root level="INFO">
        <appender-ref ref="consoleAppender" />
    </root>
</configuration>

2. Logback in Java Program

The following Java class is a very simple example that initializes, and then uses, the Logback logging library for Java applications.

package com.kruders;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
public class HelloWorld {
static final Logger logger = LoggerFactory.getLogger(HelloWorld.class);
     
    public static void main(String[] args) {
        logger.info("Hello World!!!");
    }
}

When you run the above example you’ll get an output like:

12:26:48.079 [main] INFO com.kruders.HelloWorld – Hello World!!!


No comments yet.

Leave a Reply