Spring boot logging with application.properties

Learn spring boot logging configuration via application.properties file in simple and easy to follow instructions. In the default structure of a Spring Boot web application, we can locate the application.properties file under the resources folder.

logging.level.org.springframework=DEBUG
logging.level.com.howtodoinjava=DEBUG

#output to a temp_folder/file
logging.file=${java.io.tmpdir}/application.log

# Logging pattern for the console
logging.pattern.console= %d{yyyy-MM-dd HH:mm:ss} - %msg%n

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

1. Spring boot default logging
2. Spring boot logging levels
3. Spring boot logging patterns
4. Log output to file
5. Active profiles to load environment specific logging configuration
6. Color-coded log output

1. Spring boot default logging

To understand default spring boot logging, lets put logs in spring boot hello world example. Just to mention, there is no logging related configuration in application.properties file. If we see any configuration in downloaded application, please remove it.

private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());

@RequestMapping("/")
public String home(Map<String, Object> model) {

	LOGGER.debug("This is a debug message");
	LOGGER.info("This is an info message");
	LOGGER.warn("This is a warn message");
	LOGGER.error("This is an error message");

	model.put("message", "HowToDoInJava Reader !!");
	return "index";
}

Start the application. Access application at browser and verify log messages in console.

2017-03-02 23:33:51.318  INFO 3060 --- [nio-8080-exec-1] c.h.app.controller.IndexController       : info log statement printed
2017-03-02 23:33:51.319  WARN 3060 --- [nio-8080-exec-1] c.h.app.controller.IndexController       : warn log statement printed
2017-03-02 23:33:51.319 ERROR 3060 --- [nio-8080-exec-1] c.h.app.controller.IndexController       : error log statement printed

Note down the observation that Default logging level is INFO – because debug log message is not present.
There is fixed default log message pattern which is configured in different base configuration files.

%clr{%d{yyyy-MM-dd HH:mm:ss.SSS}}{faint} %clr{${LOG_LEVEL_PATTERN}} %clr{${sys:PID}}{magenta} 
%clr{---}{faint} %clr{[%15.15t]}{faint} %clr{%-40.40c{1.}}{cyan} %clr{:}{faint} %m%n${sys:LOG_EXCEPTION_CONVERSION_WORD}

The above pattern print these listed log message parts with respective color coding applied:

  • Date and Time — Millisecond precision.
  • Log Level — ERROR, WARN, INFO, DEBUG or TRACE.
  • Process ID.
  • A — 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

2. Spring boot logging levels

When a message is logged via a Logger it is logged with a certain log level. In the application.properties file, you can define log levels of Spring Boot loggers, application loggers, Hibernate loggers, Thymeleaf loggers, and more. To set the logging level for any logger, add properties starting with logging.level.

Logging level can be one of one of TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF. The root logger can be configured using logging.level.root.

#logging.level.root=WARN

logging.level.org.springframework.web=ERROR
logging.level.com.howtodoinjava=DEBUG

In above configuration, I upgraded log level for application classes to DEBUG (from default INFO). Now observe the logs:

2017-03-02 23:57:14.966 DEBUG 4092 --- [nio-8080-exec-1] c.h.app.controller.IndexController       : debug log statement printed
2017-03-02 23:57:14.967  INFO 4092 --- [nio-8080-exec-1] c.h.app.controller.IndexController       : info log statement printed
2017-03-02 23:57:14.967  WARN 4092 --- [nio-8080-exec-1] c.h.app.controller.IndexController       : warn log statement printed
2017-03-02 23:57:14.967 ERROR 4092 --- [nio-8080-exec-1] c.h.app.controller.IndexController       : error log statement printed

3. Spring boot logging patterns

To change the logging patterns, use logging.pattern.console and logging.pattern.file properties.

# Logging pattern for the console
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} - %msg%n

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

After changing console logging pattern in application, log statements are printed as below:

2017-03-03 12:59:13 - This is a debug message
2017-03-03 12:59:13 - This is an info message
2017-03-03 12:59:13 - This is a warn message
2017-03-03 12:59:13 - This is an error message

4. Log output to file

To print the logs in file, use logging.file or logging.path property.

logging.file=c:/users/howtodoinjava/application-debug.log

Verify the logs in file.

2017-03-03 13:02:50.608 DEBUG 10424 --- [http-nio-8080-exec-1] c.h.app.controller.IndexController       : This is a debug message
2017-03-03 13:02:50.608  INFO 10424 --- [http-nio-8080-exec-1] c.h.app.controller.IndexController       : This is an info message
2017-03-03 13:02:50.608  WARN 10424 --- [http-nio-8080-exec-1] c.h.app.controller.IndexController       : This is a warn message
2017-03-03 13:02:50.609 ERROR 10424 --- [http-nio-8080-exec-1] c.h.app.controller.IndexController       : This is an error message

5. Active profiles to load environment specific logging configuration

It is desirable to have multiple configurations for any application – where each configuration is specific to a particular runtime environment. In spring boot, you can achieve this by creating multiple application-{profile}.properties files in same location as application.properties file.

Profile specific properties always override the non-profile specific ones. If several profiles are specified, a last wins strategy applies.

If I have two environments for my application i.e. prod and dev. Then I will create two profile specific properties files.

5.1. application-dev.properties

logging.level.com.howtodoinjava=DEBUG
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} - %msg%n

5.2. application-prod.properties

logging.level.com.howtodoinjava=ERROR
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} - %msg%n

To supply profile information to application, property spring.profiles.active is passed to runtime.

$ java -jar -Dspring.profiles.active=prod spring-boot-demo.jar

6. Color-coded log output

If your terminal supports ANSI, color output will be used to aid readability. You can set spring.output.ansi.enabled value to either ALWAYS, NEVER or DETECT.

Color coding is configured using the %clr conversion word. In its simplest form the converter will color the output according to the log level.

FATAL and ERROR – Red
WARN – Yellow
INFO, DEBUG and TRACE – Green

Drop me your questions in comments section.

Happy Learning !!

References:

Spring Boot – How to logging
Spring boot features – Logging

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

9 thoughts on “Spring boot logging with application.properties”

  1. Thanks for this tutorial.
    Main help here is that when we use @Slf4j we can setup a property like below example:
    logging.level.PACKAGE_ROOT = debug

  2. Hii,
    I want to append messageId to each line of log file which will be fetched from request body of microservice.How can we do that?

  3. Hi,

    I am doing a spring boot based maven project. There I implemented log4j and I am using Console Appender. I am configuring all logging code in the application.properties file. My requirement is I want to give the Buffersize and BufferIo, How to write this code please tell me. Already I wrote these things-

    #Log4j Level Order/Priority=> Trace < Debug < Info < Warn < Error < Fatal

    logging.level.root=Info
    
    logging.level.org.springframework.security=ERROR
    logging.level.org.springframework.web=ERROR
    logging.level.org.hibernate=ERROR
    
    #immediateFlush-To set if console stream being flushed with each logging output request.
    logging.console.immediateFlush=true
    
    #encoding- Over-ride the default character-encoding scheme.
    logging.console.encoding=UTF-8
    
    #target- Either System.out or System.err. The default is System.out.
    logging.console.target=System.out
    
    #pattern.console- To change logging pattern in console we need to use logging.pattern.console property.
    logging.pattern.console=%d{yyyy-MMM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{15} - %msg%n
    

    Thanks & Regards,
    Prakash Kumar Behera

  4. Hi,

    I don’t want console logs.

    So I have added

    LOG_FOLDER=** in application.conf

    logging.pattern.console=OFF in application.properties

    It is working. I mean no two logs(console,file). But does logging.pattern.console take the value OFF?

  5. Hello Lokesh Gupta,

    Could you please help me to figure out how to configure “RollingFileAppender” in application.properties file

    Thanks,
    SHameer

    • Spring boot aims to provide logging support with minimum configuration, so it provides that by making many things defaults and limited. It uses internally base.xml file. This base.xml file includes file-appender.xml. It has below configuration –

      &lt;appender name=&quot;FILE&quot;
      		class=&quot;ch.qos.logback.core.rolling.RollingFileAppender&quot;&gt;
      		&lt;encoder&gt;
      			&lt;pattern&gt;${FILE_LOG_PATTERN}&lt;/pattern&gt;
      		&lt;/encoder&gt;
      		&lt;file&gt;${LOG_FILE}&lt;/file&gt;
      		&lt;rollingPolicy class=&quot;ch.qos.logback.core.rolling.FixedWindowRollingPolicy&quot;&gt;
      			&lt;fileNamePattern&gt;${LOG_FILE}.%i&lt;/fileNamePattern&gt;
      		&lt;/rollingPolicy&gt;
      		&lt;triggeringPolicy
      			class=&quot;ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy&quot;&gt;
      			&lt;MaxFileSize&gt;10MB&lt;/MaxFileSize&gt;
      		&lt;/triggeringPolicy&gt;
      &lt;/appender&gt;
      

      You inject above properties using application.properties file-

      logging.file=c:/users/howtodoinjava/application-debug.log
      logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
      

      That’s all is possible with default logging configuration within application.properties. If you want to customize more, the you need to override the logging config in separate logback.xml file. To do so, configure config location in application.properties file and then customize config.

      logging.config= #Location of the logging configuration file

      e.g.

      &lt;configuration&gt;
        &lt;appender name=&quot;FILE&quot; class=&quot;ch.qos.logback.core.rolling.RollingFileAppender&quot;&gt;
          &lt;file&gt;${LOG_FILE}&lt;/file&gt;
          &lt;rollingPolicy class=&quot;ch.qos.logback.core.rolling.TimeBasedRollingPolicy&quot;&gt;
            &lt;!-- daily rollover --&gt;
            &lt;fileNamePattern&gt;${LOG_FILE}.%d{yyyy-MM-dd}.log&lt;/fileNamePattern&gt;
      
            &lt;!-- keep 30 days' worth of history capped at 3GB total size --&gt;
            &lt;maxHistory&gt;30&lt;/maxHistory&gt;
            &lt;totalSizeCap&gt;3GB&lt;/totalSizeCap&gt;
      
          &lt;/rollingPolicy&gt;
      
          &lt;encoder&gt;
            &lt;pattern&gt;${FILE_LOG_PATTERN}&lt;/pattern&gt;
          &lt;/encoder&gt;
        &lt;/appender&gt; 
      
        &lt;root level=&quot;DEBUG&quot;&gt;
          &lt;appender-ref ref=&quot;FILE&quot; /&gt;
        &lt;/root&gt;
      &lt;/configuration&gt;
      

Comments are closed.

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.