Logging in spring boot is very flexible and easy to configure.

Spring boot supports various logging providers through some simple configuration.

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 UtilLoggingLog4J2, 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.

spring-boot-starter-web depends on spring-boot-starter-logging, which pulls in spring-jcl for us.

spring boot logging frameworks

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 and also decouple the logging implementation from application.

 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);     } } 

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.

log4j logging hierarchy order - Stack Overflow

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.

 # 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.

 # 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.

 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% 
Pattern Part What it Means
%clr %clr specifies a colour. By default, it is based on log levels, e.g, INFO is green. If you want to specify specific colours, you can do that too.

The format is:
%clr(Your message){your colour}

So for example, if we wanted to add "Demo" to the start of every log message, in green, we would write:
%clr(Demo){green}

%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd HH:mm:ss.SSS}} %d is the current date, and the part in curly braces is the format. ${VARIABLE}:-default is a way of specifying that we should use the $VARIABLE environment variable for the format, if it is available, and if not, fall back to default. This is handy if you want to override these values in your properties files, by providing arguments, or by setting environment variables.

In this example, the default format is yyyy-MM-dd HH:mm:ss.SSS unless we specify a variable named LOG_DATEFORMAT_PATTERN. In the logs above, we can see 2020-10-19 10:09:58.152 matches the default pattern, meaning we did not specify a custom LOG_DATEFORMAT_PATTERN.

${LOG_LEVEL_PATTERN:-%5p} Uses the LOG_LEVEL_PATTERN if it is defined, else will print the log level with right padding up to 5 characters (E.g "INFO" becomes "INFO " but "TRACE" will not have the trailing space). This keeps the rest of the log aligned as it'll always be 5 characters.
${PID:- } The environment variable $PID, if it exists. If not, space.
t The name of the thread triggering the log message.
logger The name of the logger (up to 39 characters), in our case this is the class name.
%m The log message.
%n The platform-specific line separator.
%wEx If one exists, wEx is the stack trace of any exception, formatted using Spring Boot's ExtendedWhitespaceThrowableProxyConverter.
Spring Environment System Property Comments
logging.exception-conversion-word LOG_EXCEPTION_CONVERSION_WORD The conversion word used when logging exceptions.
logging.file LOG_FILE If defined, it is used in the default log configuration.
logging.file.max-size LOG_FILE_MAX_SIZE Maximum log file size (if LOG_FILE enabled). (Only supported with the default Logback setup.)
logging.file.max-history LOG_FILE_MAX_HISTORY Maximum number of archive log files to keep (if LOG_FILE enabled). (Only supported with the default Logback setup.)
logging.path LOG_PATH If defined, it is used in the default log configuration.
logging.pattern.console CONSOLE_LOG_PATTERN The log pattern to use on the console (stdout). (Only supported with the default Logback setup.)
logging.pattern.dateformat LOG_DATEFORMAT_PATTERN Appender pattern for log date format. (Only supported with the default Logback setup.)
logging.pattern.file FILE_LOG_PATTERN The log pattern to use in a file (if LOG_FILE is enabled). (Only supported with the default Logback setup.)
logging.pattern.level LOG_LEVEL_PATTERN The format to use when rendering the log level (default %5p). (Only supported with the default Logback setup.)
PID PID The current process ID (discovered if possible and when not already defined as an OS environment variable).

The following table describes the mapping of log levels to colors:

FATAL Red
ERROR Red
WARN Yellow
INFO Green
DEBUG Green
TRACE Green

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% 

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> 

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> 

This free site is ad-supported. Learn more