Thursday, December 31, 2020

A Guide to Logging in Spring Boot

 Logging in spring boot is very flexible and easy to configure. Spring boot supports various logging providers through some simple configuration. In this tutorial, we will look at various logging options and configurations supported by Spring boot.

Table of Contents

1. Default Zero Configuration Logging
2. Logback Logging
3. Log4j2 Logging
4. More examples

1. Default Zero Configuration Logging

Spring boot active enabled logging is determined by spring-boot-starter-logging artifact and it’s auto-configuration which enables anyone of supported logging providers (Java Util
Logging
Log4J2, and Logback) based on configuration provided.

If we do not provide any logging specific configuration, we will still see logs printed in “console”. These are because of default logging support provided in spring boot which uses Logback.

Spring boot’s internal logging is written with Apache Commons Logging so it is one and only mandatory dependency. Till, boot 1.x – we had to import it manually. Since boot 2.x, it is downloaded transitively. To be more precise, spring-boot-starter-web depends on spring-boot-starter-logging, which pulls in spring-jcl for us.

Spring boot auto-configuration provides default logging using Logback and it’s default configuration is provided in these config files.

1.1. Add log statements

To add log statements in application code, use org.slf4j.Logger and org.slf4j.LoggerFactory from SLF4J. It provides lots of useful methods for logging anf also decouple the logging implementation from application.

Application.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
@SpringBootApplication
public class Application
{
    private static final Logger LOGGER=LoggerFactory.getLogger(Application.class);
 
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
         
        LOGGER.info("Simple log statement with inputs {}, {} and {}", 1,2,3);
    }
}
Console
2019-07-28 12:16:57.129  INFO 3416 --- [main]
com.howtodoinjava.demo.Application: Simple log statement with inputs 1, 2 and 3

1.2. Logging Level

Logback supports ERRORWARNINFODEBUG, or TRACE as logging level. By default, logging level is set to INFO. It means that code>DEBUG and TRACE messages are not visible.

To enable debug or trace logging, we can set the logging level in application.properties file. Also, we can pass the –debug or –trace arguments on the command line while starting the application.

Configuration
# In properties file
debug=true
 
# In Console
$ java -jar target/my-app-0.0.1-SNAPSHOT.jar --trace

We can apply logging levels to specific packages as well. It can be done either in console or application.properties file.

Configuration
# In Console
-Dlogging.level.org.springframework=ERROR
-Dlogging.level.com.howtodoinjava=TRACE
 
# In properties file
logging.level.org.springframework=ERROR
logging.level.com.howtodoinjava=TRACE

If the log level for a package is defined multiple times with different log levels, the lowest level will be used. TRACE is lowest and ERROR is highest.

1.3. Log format

The default log statement formatting is mentioned in defaults.xml file.

defaults.xml
<conversionRule conversionWord="clr"
converterClass="org.springframework.boot.logging.logback.ColorConverter" />
 
<conversionRule conversionWord="wex"
converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />
 
<conversionRule conversionWord="wEx"
converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />
 
<property name="CONSOLE_LOG_PATTERN" value="${CONSOLE_LOG_PATTERN:-%clr(%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd HH:mm:ss.SSS}})
{faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39})
{cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
 
<property name="FILE_LOG_PATTERN" value="${FILE_LOG_PATTERN:-%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd HH:mm:ss.SSS}}
${LOG_LEVEL_PATTERN:-%5p} ${PID:- } --- [%t] %-40.40logger{39} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>

It outputs following information.

  • Date and Time: Millisecond precision and easily sortable.
  • Log LevelERRORWARNINFODEBUG, or TRACE.
  • Process ID.
  • --- separator to distinguish the start of actual log messages.
  • Thread name: Enclosed in square brackets (may be truncated for console output).
  • Logger name: This is usually the source class name (often abbreviated).
  • The log message.

To customize the log format, use logging.pattern.console and logging.pattern.file properties.

application.properties
# 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%

1.4. Logging to file

By default spring boot logs to console only. If we want to enable file logging, we can easily do it using simple property logging.file or logging.path.

When using logging.path, it will create a file named spring.log in mentioned package.

application.properties
# Output to a temp_folder/file
logging.file=c:/temp/application.log
 
#logging.path=/my-folder/
 
# Logging pattern for file
logging.pattern.file= %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%

2. Logback Logging

The default logging is good enough for most usecases. But sometimes in enterprise applications, we need more fine control over logging with other complex requirements. In that case, having a dedicated logging configuration is suitable.

Spring boot by default uses logback, so to customize it’s behavior, all we need to add only logback.xml in classpath and define customization over the file.

logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
 
    <property name="LOG_LOCATION" value="c:/temp" />
 
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss} - %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>
 
    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <File>{LOG_LOCATION}/mylog.log</File>
        <encoder>
             <pattern>%d{yyyy-MM-dd HH:mm:ss} - %logger{36} - %msg%n</pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_LOCATION}/archived/mylog-%d{yyyy-MM-dd}.%i.log
            </fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy
                class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>10MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
    </appender>
 
    <root level="INFO">
        <appender-ref ref="CONSOLE"/>
        <appender-ref ref="FILE"/>
    </root>
 
    <!-- Application logs at trace level -->
    <logger name="com.howtodoinjava" level="trace" additivity="false">
        <appender-ref ref="RollingFile" />
        <appender-ref ref="Console" />
    </logger>
 
</configuration>

3. Log4j2 Logging

Step 1: Exclude logback and include log4j2

As mentioned earlier, spring boot uses logback as default. So if we have to use any other logging framework e.g. log4j2, we must exclude logback from classpath of the application. Also, add spring-boot-starter-log4j2 to classpath.

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

Step 2: Add log4j2 configuration file

Now, add log4j2 specific configuration file in classpath (typically in resources folder). It can be named as any of the following:

  • log4j2-spring.xml
  • log4j2.xml

If we have logging configuration in any other file (e.g. log4j2.properties, applogs.xml etc), we can use logging.file property to specify it’s path application.properties file.

log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
    <Properties>
        <Property name="LOG_PATTERN">%d{yyyy-MM-dd'T'HH:mm:ss.SSSZ} %p %m%n</Property>
        <Property name="APP_LOG_ROOT">c:/temp</Property>
    </Properties>
    <Appenders>
        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout pattern="${LOG_PATTERN}" />
        </Console>
  
        <RollingFile name="file"
            fileName="${APP_LOG_ROOT}/SpringBoot2App/application.log"
            filePattern="${APP_LOG_ROOT}/SpringBoot2App/application-%d{yyyy-MM-dd}-%i.log">
            <PatternLayout pattern="${LOG_PATTERN}" />
            <Policies>
                <SizeBasedTriggeringPolicy size="19500KB" />
            </Policies>
            <DefaultRolloverStrategy max="1" />
        </RollingFile>
  
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="console" />
            <AppenderRef ref="file" />
        </Root>
    </Loggers>
</Configuration>

Step 3: With or without Slf4j

By default, if you are using SLF4J logger classes i.e. org.slf4j.Logger and org.slf4j.LoggerFactory, nothing needs to be changed in application code and all log statement will continue printing in target appenders.

If you are targeting to use log4j2 specific classes only, use org.apache.logging.log4j.Logger and org.apache.logging.log4j.LogManager.

I will recommend to use SLF4J logger classes.

SLF4J logger classes
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
@SpringBootApplication
public class Application
{
    private static final Logger LOGGER = LoggerFactory.getLogger(Application.class);
 
    public static void main(String[] args) {       
        SpringApplication.run(Application.class, args);
 
        LOGGER.info("Simple log statement with inputs {}, {} and {}", 1,2,3);
    }
}
LOG4J2 logger classes
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
 
@SpringBootApplication
public class Application
{
    private static Logger LOGGER = LogManager.getLogger(Application.class);
 
    public static void main(String[] args) {       
        SpringApplication.run(Application.class, args);
 
        LOGGER.info("Simple log statement with inputs 1, 2 and 3");
    }
}

No comments:

Post a Comment

How to DROP SEQUENCE in Oracle?

  Oracle  DROP SEQUENCE   overview The  DROP SEQUENCE  the statement allows you to remove a sequence from the database. Here is the basic sy...