:::: MENU ::::

Logback


Logback is a logging technology used in Java projects.

Installation

A basic Java SE project will serve to demonstrate the use of this tool. Create a Maven Project (skip archetype selection) and add these dependencies to the pom.xml file:

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

Basic Configuration

We need to create a file called logback.xml and put it in the classpath (/src/main/resources, for example). In this file we are going to configure an appender that will write on the console.

logback.xml

<configuration>

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
  </appender>

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

Basic example

In this example we well create a logger from the logger factory and we will output a debug simple message.

LogbackDemo.java

com.luisgomezcaballero.logbackdemo;

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

public class LogbackDemo {

  public static void main(String[] args) {

    Logger logger = LoggerFactory.getLogger(LogbackDemo.class);
    logger.debug("Basic example.");

  }
}

Advanced Configuration

Now we will configure a standard console appender, and then, a file appender.

logback.xml

<configuration>

  <appender name="FILE" class="ch.qos.logback.core.FileAppender">
    <file>logfile.txt</file>
    <encoder>
      <pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n</pattern>
    </encoder>
  </appender>

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n</pattern>
    </encoder>
  </appender>

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

Advanced example

This file is the same as in the basic example, but with the advanced config the message will be printed on the console and in the log file “logfile.txt” too.
LogbackDemo.java

com.luisgomezcaballero.logbackdemo;

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

public class LogbackDemo {

  public static void main(String[] args) {

    Logger logger = LoggerFactory.getLogger(LogbackDemo.class);
    logger.debug("Advanced example.");

  }
}

Running the project

Click on Run As/Java application.

That will print on the console and in the file the debug message.

Basic:

22:18:57.545 [main] DEBUG c.l.logbackdemo.LogbackDemo - Basic example.

Advanced:

2018-09-30 22:20:31,444 DEBUG [main] c.l.l.LogbackDemo [LogbackDemo.java:11] Advanced example.

Repository

This demo project is available at https://github.com/luisgomezcaballero/logbackdemo.


So, what do you think ?