How to write log messages to file using Spring Boot?

Spring Boot allows you to configure some basic aspects of your logging system using application.properties, but there are limits:

To configure the more fine-grained settings of a logging system you need to use the native configuration format supported by the LoggingSystem in question.

In other words, if you want to do something that isn’t specifically supported through properties you won’t get around to adding and editing a logback.xml file (assuming you’re using logback).

So, let’s go through your requirements:

  1. “I want to log message in a file not on console.”

According to the docs:

By default, Spring Boot will only log to the console and will not write log files. If you want to write log files in addition (emphasis added) to the console output you need to set a logging.file or logging.path property (for example in your application.properties).

In other words, not logging to the console cannot be done using properties.

  1. “I am getting log messages of info only in my application.log file but I want error as well as debug messages as well.”

By default Spring Boot logs on INFO level, which should include ERROR, are you sure you’re not getting ERROR logs with the default setting?

Also, you only specify the highest level you want to log, not each level, and you have to specify the logger you want to set the level on.

This won’t work:

logging.level: DEBUG
logging.level: ERROR

This is an example how to configure custom log levels according to the docs:

logging.level.org.springframework.web: DEBUG
logging.level.org.hibernate: ERROR

You can also use the logging.level.* property to set the level of the root logger like this:

logging.level.ROOT: DEBUG

Note that setting DEBUG logging on the ROOT logger will generate a large amount of logs. I’ve just tested it here and got roughly 13MB of logs just on startup, without doing anything.

  1. “I want error message in error.log file and debug message in debug.log and info messages in info.log.”

Again, this cannot be done using properties alone. Spring Boot allows you to configure exactly one logging.file property which will contain all the logs.

For a complete list of logging properties available and sample values see here.

Leave a Comment

tech