1. Overview

Logging is the recording of intended execution steps in the software lifecycle. It makes troubleshooting, monitoring and debugging of software easier and smooth. There are many java based logging frameworks available like Log4j, Logback, Java Logging(JUL), Apache Common Logging for implement logging functionality in Java frameworks. Log4j2 is an upgraded version of the Log4j framework.

In this tutorial, we will learn how to setup Log4j2 logging framework with Spring Boot project.

2. Example

2.1 Project Structure

Project Structure for Spring Boot and Log4j2

Project Structure for Spring Boot and Log4j2

2.2 POM file configuration

Add spring-boot-starter-log4j2 dependency in pom.xml or gradle file.

If you are using spring-boot-starter-web artifact in spring boot then you need to exclude spring-boot-starter-logging dependency in pom.xml as per below xml.

<?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">


   <description>Spring Boot Log4j2 Example</description>







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.log4j.controller;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

public class Log4JExample {

    private static final Logger = LogManager.getLogger(Log4JExample.class);

    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.fatal("This is a fatal log example");
        logger.warn("This is a warn log example");
        return "Check the Console Logs";

2.4 application.properties

Add the path of Log4j2 configuration file which guide spring boot log4j2 framework for configuration.


2.5 log4j2.properties

Create log4j2.properties configuration file in the resource folder. Log4j2 can be also configured by other types of files like XML, YAML, JSON.

2.5.1 Configure log4j2.properties file

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 the console, file, JDBC, etc.
3). Layout: It prints logs using the configured format like PatternLayout, HTMLLayout, etc.

Here first we configure only Console logs as shown below.  Add below configuration into log4j2.propeties file.

appenders = console 

appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = [%-5level] %d{dd-MM-yyyy hh:mm:ss.SSS a} [%t] %c{1} - %msg%n

rootLogger.level = ERROR
rootLogger.appenderRefs = STDOUT
rootLogger.appenderRef.stdout.ref = STDOUT

loggers = controller

logger.controller.name = com.javadeveloperzone.log4j.controller
logger.controller.level = ALL

logger.controller.appenderRefs = STDOUT
logger.controller.additivity = true
logger.controller.appenderRef.stdout.ref = STDOUT

Here, we have used the console as logging output Appender, configure appenders = console. You can use other appender like a file, rollingfile, JDBC, etc.

We have set PatternLayout and configured patterns for log format. In this pattern format:

  • a level is for Log level like DEBUG, ERROR, etc.
  • Date Format dd-MM-yyyy hh:mm:ss.SSS a is for logging date format
  • t for Thread name
  • c for the category of the logging event
  • msg for Message
  • n for a new line.
  • For info related to layout configuration: https://logging.apache.org/log4j/2.x/manual/layouts.html

For Logger configuration, we can set the whole system logging level by rootLogger.level. There possible values for logging level are DEBUG, ERROR, FATAL, TRACE, WARN, ALL, INFO, OFF.

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


For example: If your log level set to WARN then your logging appender will show you WARN, ERROR and FATAL types of logs.

If you want to set the logging level for the particular package then you need to define separate loggers and logger for that. We have set ALL logging level for com.javadeveloperzone.log4j.controller package means all types of logs will be captured from classes that package.

2.5.2 Output

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

Check console of your IDE. The output will as per below:

[TRACE] 15-07-2018 02:06:37.586 PM [http-nio-8080-exec-1] Log4JExample - This is a trace log example
[INFO ] 15-07-2018 02:06:37.602 PM [http-nio-8080-exec-1] Log4JExample - This is an info log example
[DEBUG] 15-07-2018 02:06:37.602 PM [http-nio-8080-exec-1] Log4JExample - This is a debug log example
[ERROR] 15-07-2018 02:06:37.602 PM [http-nio-8080-exec-1] Log4JExample - This is an error log example
[FATAL] 15-07-2018 02:06:37.602 PM [http-nio-8080-exec-1] Log4JExample - This is a fatal log example
[WARN ] 15-07-2018 02:06:37.602 PM [http-nio-8080-exec-1] Log4JExample - This is a warn log example

2.5.3 Configure log4j2.properties file for logging Output in the File

If you want to store logging output in the file then you need to add file appender in log4j2.properties file. Append below five lines of appender.file code to log4j2.properties file. Replace last three line of logger.controller in  log4j2.properties  with given below last three line of code of logger.controller.

appender.file.type = File
appender.file.name = LOGFILE
appender.file.layout.pattern= [%-5level] %d{dd-MM-yyyy hh:mm:ss.SSS a} [%t] %c{1} - %msg%n

logger.controller.appenderRefs = LOGFILE
logger.controller.additivity = true
logger.controller.appenderRef.file.ref = LOGFILE

Using the above configuration logs will be stored in logs/logfile.log. If you want to avoid repetition same of logs in appenders, you can set  logger.controller.additivity = false. So, your logs for a configured package will be stored only in logs/logfile.log only, it will not be shown in the console.

3. Conclusion

In this article, we learned how to configure Log4j2 in Spring Boot with use of properties file. Main things we need to keep in mind when configuring log4j2 with Spring Boot is selection of appender, layout and logger scope with level.

4. References

5. Source Code

spring-boot-log4j2-example (11 KB)

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

Leave a Reply

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