1. Overview

Slf4j (Simple Logging Facade for Java) APIs provides abstraction using facade design pattern for supporting different logging frameworks like Logback, Log4j, Java Logging, etc. Using Slf4j, the software can be independent from the dependency of logging implementation frameworks and it can be configured to use any logging implementation frameworks which it supports. It allows to plugin logging system at deployment time.

In this tutorial, we will learn how to setup Slf4j with Logback framework in Spring Boot project.

2. Example

2.1 Project Structure

Project Structure for Spring Boot with Slf4j and Logback

2.2 POM file configuration

If you are using spring-boot-starter-web artifact in spring boot then you do not need to add any other dependency for Slf4j and Logback. Because, spring-boot-starter-web already contains dependency of spring-boot-starter-logging which contains dependencies of logback and slf4j.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>

   <groupId>com.javadeveloperzone</groupId>
   <artifactId>slf4j</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>

   <name>slf4j</name>
   <description>Spring Boot with Slf4j and Logback Example</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.0.3.RELEASE</version>
      <relativePath/> 
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>

2.3 Controller

Create Controller File where Logging can be performed. Logging can be performed in any Java file but for ease we have taken Controller for different levels of logging test.

package com.javadeveloperzone.slf4j.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class SLF4JExample {
    private static final Logger logger = LoggerFactory.getLogger(SLF4JExample.class);

    @RequestMapping("/")
    @ResponseBody
    public String testMethod() {

        logger.trace("This is a trace log example");
        logger.info("This is an info log example");
        logger.debug("This is a debug log example");
        logger.error("This is an error log example");
        logger.warn("This is a warn log example");

        return "Check the Console Logs";
    }
}
  • Main things to notice here is get Logger object by LoggerFactory rather than LogManager of logging implementation. We not directly coupling with logging implementation framework. Here, we are using LoggerFactory of Slf4j API proving loose coupling with implementation.
  • We can configure any java logging framework with project which is supported by Slf4j.

2.4 logback-spring.xml

Create logback-spring.xml configuration file in the resource folder. Logback can be also configured by logback.groovy.

Here, you should keep in mind three things: 1). Logger 2). Appender 3).Layout

1). Logger: It captures logs like debug log, error log, etc in defined scope.
2). Appender: It appends log to configured appender like console, file, jdbc, etc.
3). Layout: It prints logs using the configured format like PatternLayout, HTMLLayout, etc.

Here first we configured Console and File appenders.

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>[%-5level] %d{dd-MM-yyyy hh:mm:ss.SSS a} [%thread]  %logger{50} - %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>logs/logFile.log</file>
        <encoder>
            <pattern>[%-5level] %d{dd-MM-yyyy hh:mm:ss.SSS a} [%thread]  %logger{50} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="ERROR">
        <appender-ref ref="STDOUT" />
    </root>

    <logger name="com.javadeveloperzone.slf4j.controller" level="ALL" additivity="true">
        <appender-ref ref="FILE"/>
    </logger>
</configuration>

Here, we have defined two Appenders ConsoleAppender and FileAppender. You can use other appender like RollingFile, DB, SMTP, etc. File path for logfile has been defined in <file>logs/logFile.log</file> tag.

Here encoder takes default layout as PatternLayout. In this pattern format:

  • level is for Log level like DEBUG, ERROR, etc.
  • Date Format dd-MM-yyyy hh:mm:ss.SSS a is for logging date format
  • thread for Thread name
  • logger for logger name – numbers behind that define how much specific classname you needed.
  • msg for Message
  • n for new line.

For info related to layout configuration: https://logback.qos.ch/manual/layouts.html

For Logger configuration, we can set whole system logging level by <root level="ERROR">. There possible values for logging level are DEBUG, ERROR, TRACE, WARN, ALL, INFO, OFF.

Visibility of logs based on logging levels are as per below table:

Log Levels TRACE DEBUG INFO WARN ERROR
TRACE
DEBUG
INFO
WARN
ERROR
ALL
OFF

 

  • For example: If your log level set to INFO then your logging appender will show you INFO, WARN, ERROR types of logs.
  • If you want to set logging level for particular package then you need to define separate loggers and logger for that. We have set ALL logging level for javadeveloperzone.log4j.controller package means that all types of logs will be captured from classes that package.
  • If you set additivity="false" in logger tag, your logs for the configured package will be stored only in logs/logFile.log only, it will not be shown in console.
  • Note: you can change the logging system to log4j2, java logging, etc and you need to change in Java code. You need to just change configuration. Example: If need to add support for log4j2 then you just need to exclude spring-boot-starter-logging from pom file and add log4j2 configuration file.

2.5 Output

Run mvn spring-boot run command and run spring boot application. Open localhost:8080/ url in the browser.

Check console of your IDE and logs/logFile.log. Output will as per below:

[TRACE] 15-07-2018 08:05:48.904 PM [http-nio-8080-exec-1]  c.javadeveloperzone.slf4j.controller.SLF4JExample - This is a trace log example
[INFO ] 15-07-2018 08:05:48.919 PM [http-nio-8080-exec-1]  c.javadeveloperzone.slf4j.controller.SLF4JExample - This is an info log example
[DEBUG] 15-07-2018 08:05:48.919 PM [http-nio-8080-exec-1]  c.javadeveloperzone.slf4j.controller.SLF4JExample - This is a debug log example
[ERROR] 15-07-2018 08:05:48.919 PM [http-nio-8080-exec-1]  c.javadeveloperzone.slf4j.controller.SLF4JExample - This is an error log example
[WARN ] 15-07-2018 08:05:48.919 PM [http-nio-8080-exec-1]  c.javadeveloperzone.slf4j.controller.SLF4JExample - This is a warn log example

3. Conclusion

In this article, we learned how to configure Slf4j with Logback in Spring Boot with XML file. Slf4j is a facade layer for providing support for different types of Logging implementation in java. Your code can be written without tight coupling of logging framework.

4. References

5. Source Code

spring-boot-slf4j-logback-example (10 KB)

Was this post helpful?
Let us know, if you liked the post. Only in this way, we can improve us.
Yes
No

Leave a Reply

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