Blog |

Spring Boot Logging

Spring Boot Logging
Table of Contents

Logging in Spring Boot is very flexible and easy to configure. Spring Boot uses Apache Commons Logging for internal logging but allows developers to configure the underlying log implementation. Various logging providers are supported through simple configuration.

Spring Boot provides default configurations for Java Util Logging, Log4J2 and Logback. Each logging provider is preconfigured to use console output with optional file output available as well. Spring Boot applications need to collect log data to help troubleshoot and fix issues in code, as well as measure business metrics.

Zero Configuration Logging

Spring Boot auto-tunes the majority of the configuration settings within an application so that developers can focus on the code.

The only required dependency for logging using Spring Boot is Apache Commons Logging. When using Spring Boot 2.x, the spring-boot-starter-logging starter pulls in the spring-jcl module, which contains the Apache Commons Logging provider. If using Spring Boot 1.x, Apache Commons Loggingem> needs to be imported explicitly.

When Spring Boot starters are used, Logback is used for logging by default. The default Logback implementation logs the output to the console at the info level. Logback routing is included as well to ensure support for Apache Commons Logging, Java Util Logging, Log4J and SLF4J.

Spring Boot Logging Levels

A logger logs a message with a specific logging level. Spring Boot provides the following logging levels:

  • TRACE
  • DEBUG
  • INFO
  • WARN
  • ERROR

All supported logging providers can have the logging level set in the Spring Environment using the following syntax:

logging.level.loggername=level

The root logger can be configured using logging.level.root.

Here is an example for configuring the root logging level in the application.properties file:

logging.level.root = WARN
Logging.level.org.springframework.web = DEBUG

It is also possible to set the logging level using environment variables. For example, LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_WEB = ERROR will set org.springframework.webR logging level to ERROR.

Spring Boot Log Format

The default Spring Boot log format is shown below:

2021-07-08 13:25:09.187  INFO 9769 --- [main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2021-07-08 13:25:09.198  INFO 9769 --- [main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2021-07-08 13:25:09.198  INFO 9769 --- [main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.48]
2021-07-08 13:25:09.276  INFO 9769 --- [main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2021-07-08 13:25:09.276  INFO 9769 --- [main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1005 ms
2021-07-08 13:25:09.616  INFO 9769 --- [main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''

Which contains the following information:

  • Date and Time
  • Log level (TRACE, DEBUG, INFO, WARN or ERROR)
  • Process ID
  • The separator --- to distinguish the start of the log message
  • Thread name enclosed within square brackets []
  • Logger name showing the source class
  • Log message

The log format can be customized using the logging.pattern.console and logging.pattern.file properties in application.properties, for example:

# Logging pattern for the console
logging.pattern.console= %d{yyyy-MM-dd HH:mm:ss} - %logger{36} - %msg%n
# Logging pattern for file
logging.pattern.file= %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%

Applying the above property changes the console log format to the following:

2021-07-08 13:41:04 - o.s.b.w.e.tomcat.TomcatWebServer - Tomcat initialized with port(s): 8080 (http)
2021-07-08 13:41:04 - o.a.catalina.core.StandardService - Starting service [Tomcat]
2021-07-08 13:41:04 - o.a.catalina.core.StandardEngine - Starting Servlet engine: [Apache Tomcat/9.0.48]
2021-07-08 13:41:04 - o.a.c.c.C.[Tomcat].[localhost].[/] - Initializing Spring embedded WebApplicationContext
2021-07-08 13:41:04 - o.s.b.w.s.c.ServletWebServerApplicationContext - Root WebApplicationContext: initialization completed in 955 ms
2021-07-08 13:41:04 - o.s.b.w.e.tomcat.TomcatWebServer - Tomcat started on port(s): 8080 (http) with context path ''

Spring Boot Log to File and Console

Spring Boot logs to only the console by default. File logging is supported and can be enabled using the logging.file or logging.path properties in application.properties.

The log file path can be specified using the logging.path property as shown below. When using this property, a file named spring.log will be created in the specified location:

logging.path = /tmp/

The log file name can be specified using the logging.filecode> property:

logging.file = /tmp/application.log

Logback Spring Boot Configuration

The default logging configuration may not be sufficient for applications in production. A dedicated logging configuration may be needed for more fine control over logging.

Since Spring Boot uses Logback by default, when a file in the classpath has one of the following names, it will automatically be loaded over the default configuration:

  • logback-spring.xml
  • logback.xml
  • logback-spring.groovy
  • logback.groovy

The -spring variant is recommended whenever possible.

Here is an example of a simple logback-spring.xml implementation:

<----?xml version="1.0" encoding="UTF-8"?---->

    
    

    
        
            
                %d{yyyy-MM-dd HH:mm} - %logger{36} - %msg%n
            
        
    

    
        ${LOGS}/application.log
        
            %d{yyyy-MM-dd HH:mm} - %logger{36} - %msg%n
        

        
            ${LOGS}/archived/application-%d{yyyy-MM-dd}.%i.log
            
            
                10MB
            
        
    

    
        
        
    

    
        
        
    
    

Here is the output when the application is run with the above configuration:

2021-07-08 14:40 - o.s.b.w.e.tomcat.TomcatWebServer - Tomcat initialized with port(s): 8080 (http)
2021-07-08 14:40 - o.a.coyote.http11.Http11NioProtocol - Initializing ProtocolHandler ["http-nio-8080"]
2021-07-08 14:40 - o.a.catalina.core.StandardService - Starting service [Tomcat]
2021-07-08 14:40 - o.a.catalina.core.StandardEngine - Starting Servlet engine: [Apache Tomcat/9.0.48]
2021-07-08 14:40 - o.a.c.c.C.[Tomcat].[localhost].[/] - Initializing Spring embedded WebApplicationContext
2021-07-08 14:40 - o.s.b.w.s.c.ServletWebServerApplicationContext - Root WebApplicationContext: initialization completed in 1026 ms
2021-07-08 14:40 - o.a.coyote.http11.Http11NioProtocol - Starting ProtocolHandler ["http-nio-8080"]
2021-07-08 14:40 - o.s.b.w.e.tomcat.TomcatWebServer - Tomcat started on port(s): 8080 (http) with context path ''

Log4J Spring Boot configuration

Spring Boot includes routing to other logging frameworks to make it easy to switch to them. To be able to use any other logging framework, Logback needs to be excluded from the application dependencies. Also, the alternative library or starter (in this case spring-boot-starter-log4j2) needs to be added to the classpath:

<---dependency--->
org.springframework.boot
spring-boot-starter-web
<---exclusions--->
<---exclusion--->
org.springframework.boot
spring-boot-starter-logging
<---/exclusion--->
<---/exclusions--->
<---/dependency--->
<---dependency--->
org.springframework.boot
spring-boot-starter-log4j2
<---/dependency--->

The log4j2 configuration file can now be added to the classpath, which can be named as any one of the following:

  • log4j2-spring.xml
  • log4j2.xml

Here is an example of a simple log4j2-spring.xml implementation:

<---?xml version="1.0" encoding="UTF-8"?--->
<---Configuration--->
    <---Properties--->
        <---Property name="LOGS">./logs<---/Property--->
        <---Property name="LOG_PATTERN">%d{yyyy-MM-dd HH:mm} %p %m%n<---/Property--->
    <---/Properties--->

    
        
            
        

        
            
            
                
            
        
    

    
        
            
            
        
    
<---/Configuration--->

Here is the output when the application is run with the above configuration:

2021-07-10 15:20 INFO Tomcat initialized with port(s): 8080 (http)
2021-07-10 15:20 INFO Initializing ProtocolHandler ["http-nio-8080"]
2021-07-10 15:20 INFO Starting service [Tomcat]
2021-07-10 15:20 INFO Starting Servlet engine: [Apache Tomcat/9.0.48]
2021-07-10 15:20 INFO Initializing Spring embedded WebApplicationContext
2021-07-10 15:20 INFO Root WebApplicationContext: initialization completed in 853 ms
2021-07-10 15:20 INFO Starting ProtocolHandler ["http-nio-8080"]
2021-07-10 15:20 INFO Tomcat started on port(s): 8080 (http) with context path ''

SLF4J Spring Boot configuration

Log4j2 can be configured to be used with or without SLF4J. To use it, the SLF4J logger classes org.slf4j.Logger and org.slf4j.LoggerFactory can be used in application code and all log statements will output the logs to the target appenders

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

@SpringBootApplication
public class DemoApplication {
    private static final Logger LOGGER = LoggerFactory.getLogger(DemoApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

To use Log4j2 natively without SLF4J, the log4j2 native logger classes org.apache.logging.log4j.Logger and org.apache.logging.log4j.LogManager can be used:

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

@SpringBootApplication
public class DemoApplication {
    private static final Logger LOGGER = LogManager.getLogger(DemoApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

No other modification needs to be made in the Log4j2 Spring Boot configuration.

Track, Analyze and Manage Spring Boot Errors With Rollbar

Rollbar in action

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates Spring Boot error monitoring and triaging, making fixing errors easier than ever. Try it today.

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape