Spring Boot uses Commons Logging for comprehensive logging internally, but leaves the underlying logging implementation open. Default configurations are provided for Java Util Logging, Log4J2 and Logback. In each case, logging managers are pre-configured to use console output with the option of outputting to a file.

By default, if Starters are used, Logback is used for logging. Appropriate Logback routing is also provided to ensure correct operation of dependent libraries that use Java Util Logging, Commons Logging, Log4J or SLF4J.

There are many logging frameworks available for Java . Don't worry if the above list is confusing. Typically there is no need to change logging dependencies, and Spring Boot's default settings work just fine.
If you are deploying your application in a servlet container or on a server applications, logging done using the Java Util Logging API is not routed to the application logs. This prevents the application's logs from recording entries executed by the container or other applications that have been deployed to it.

Logger Format

The default log output in Spring Boot is similar to the following example:

2022-10-20 12:40:11.311  INFO 16138 --- [           main] o.s.b.d.f.s.MyApplication                : Starting MyApplication using Java 1.8.0_345 on myhost with PID 16138 (/opt/apps/myapp.jar started by myuser in /opt/apps/)
2022-10-20 12:40:11.330  INFO 16138 --- [           main] o.s.b.d.f.s.MyApplication                : No active profile set, falling back to 1 default profile: "default"
2022-10-20 12:40:13.056  INFO 16138 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2022-10-20 12:40:13.070  INFO 16138 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-10-20 12:40:13.070  INFO 16138 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.68]
2022-10-20 12:40:13.178  INFO 16138 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-10-20 12:40:13.178  INFO 16138 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1762 ms
2022-10-20 12:40:13.840  INFO 16138 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2022-10-20 12:40:13.850  INFO 16138 --- [           main] o.s.b.d.f.s.MyApplication                : Started

The following elements are output:

  • Date and time: millisecond accuracy and easy sorting.

  • Log level: ERROR, WARN, INFO, DEBUG or TRACE.

  • Process ID.

  • Separator --- to separate the beginning of the actual log messages.

  • Stream name: enclosed in square brackets (can be truncated for console output).

  • Log manager name: usually the name of the original class (often shortened).

  • Log message .

Logback does not have a FATAL level. It is displayed as ERROR.

Console output

In the default log configuration, messages are reflected to the console as they are written. By default, messages at the ERROR, WARN and INFO levels are written to the log. You can also enable "debug" mode by running the application with the --debug flag.

$ java -jar myapp.jar --debug
You can also set debug=true in the application.properties file.

If debug mode is enabled, a set of core logging managers (built-in container, Hibernate and Spring Boot) are configured to output additional information. Enabling debug mode does configure the application to log all messages at level DEBUG.

You can also enable "trace" mode by running the application with the --trace (or trace=true in the application.properties file). This allows you to log trace logs for a number of major logging managers (the built-in container, Hibernate schema generation, and the entire Spring portfolio).

Color-highlighted output

If the terminal supports ANSI, this is used to make it easier to read color output. You can install spring.output.ansi.enabled in supported value to override automatic detection.

Color encoding is configured using the conversion word %clr. In its simplest form, the converter colors the output according to the log level, as shown in the following example:

%clr(%5p)

The following table describes the correspondence between log levels and colors:

Level Color

FATAL

Red

ERROR

Red

WARN

Yellow

INFO

Green

DEBUG

Green

TRACE

Green

You can also specify the color or style you want to use , specifying it as a parameter for the conversion. For example, to make the text yellow, use the following configuration:

 %clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){yellow}

The following colors and styles are supported:

  • blue

  • cyan

  • faint

  • green

  • magenta

  • red

  • yellow

Output to a file

By default, Spring Boot logs only in the console and does not write to log files. If you need to write to log files in addition to output to the console, you must set the logging.file.name or logging.file.path property (for example, in the file application.properties).

The following table shows how the logging.* properties can be used together:5

Table 5 Logging properties
logging.file.name logging.file.path Example Description

(absent)

(absent)

Displays log entries exclusively to the console.

Specific file

(absent)

my.log

Writes to the specified log file. The names can be an exact location or be associated with the current directory.

(missing)

Specific directory

/var/log

Writes spring.log to the specified directory. The names can be an exact location or be associated with the current directory.

Log files are rotated if they reach 10 MB in size, and, like in the case of console output, messages at the ERROR, WARN and INFO levels are logged by default.

Logging properties are independent of the actual logging infrastructure. Therefore, specific configuration keys (for example, logback.configurationFile for Logback) are not controlled by Spring Boot.

File rotation

If you are using Logback, you can fine-tune log rotation parameters using the application.properties or application.yaml file. For all other logging systems, you will need to configure the rotation parameters yourself (for example, if you are using Log4J2, you can add the file log4j2.xml or log4j2-spring.xml).

The following rotation policy properties are supported:

Name Description

logging.logback.rollingpolicy.file-name-pattern

File name pattern used to create log archives.

logging.logback.rollingpolicy.clean-history-on-start

If the log archive should be cleaned when the application starts.

logging.logback.rollingpolicy.max-file-size

The maximum size of a log file before archiving it.

logging.logback.rollingpolicy.total-size-cap

Maximum size of the log archive to be deleted before actual deletion.

logging.logback.rollingpolicy.max-history

Maximum number of files in the log archive that need to be stored (default 7).

Logging Levels

All supported logging systems can have logging levels set to Environment from Spring (for example, application.properties) using logging.level.<logger-name>=<level>, where level is one of the levels, including TRACE , DEBUG, INFO, WARN, ERROR, FATAL or OFF. You can configure the root logging manager using logging.level.root.

The following example shows possible logging options in application.properties:

Properties
logging.level.root=warn
logging.level.org.springframework.web=debug
logging .level.org.hibernate=error
Yaml
logging:
    level:
        root: "warn"
        org.springframework.web: "debug"
        org.hibernate: "error"

You can also set logging levels using environment variables. For example, LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_WEB=DEBUG will set org.springframework.web to DEBUG.

The above approach will only work for package-level logging. Because loose binding always converts environment variables to lower case, it is not possible to configure logging for a single class in this way. If you want to configure logging for a class, you can use the SPRING_APPLICATION_JSON variable.

Log Groups

In many cases, it is useful to be able to group related logging managers together so that they could be configured simultaneously. For example, you can frequently change the logging levels for all logging managers associated with Tomcat, but you won't be able to easily remember the top-level packages.

To help with this, Spring Boot allows you to define groups logging in your Environment for Spring. For example, here's how you can define a "tomcat group" by adding it to your application.properties file:

Properties
logging.group.tomcat=org.apache.catalina,org.apache.coyote,org.apache.tomcat
Yaml
logging:
    group:
        tomcat:"org.apache.catalina,org.apache.coyote,org.apache.tomcat"

Once defined, you can change the level for all logging managers in a group with one line:

Properties
logging.level.tomcat=trace
Yaml
logging:
    level:
        tomcat: "trace"

Spring Boot contains the following predefined logging groups that can be used out of the box:

Name Log Managers

web

org.springframework.core.codec, org.springframework.http, org.springframework.web, org.springframework.boot.actuate.endpoint.web, org.springframework.boot.web.servlet.ServletContextInitializerBeans

sql

org.springframework.jdbc.core, org.hibernate.SQL, org.jooq.tools.LoggerListener

Using a log shutdown interceptor

To free up logging resources when an application shuts down, there is a shutdown interceptor that runs clearing the logging system when exiting the JVM. This completion hook is registered automatically unless your application is deployed as a war file. If your application has a complex hierarchy of contexts, a completion interceptor may not meet your needs. If it does not match them, disable the completion interceptor and consider the options provided directly by the underlying logging system. For example, Logback provides context selectors that allow each Logger to be created in its own context. You can use the logging.register-shutdown-hook property to disable the shutdown hook. Setting the value to false disables logging. You can set this property in the application.properties or application.yaml file:

Properties
logging.register-shutdown-hook=false
Yaml
logging:
    register-shutdown-hook: false

Custom log configuration

Various logging systems can be activated by enabling relevant libraries in the classpath and further specifically configured by passing the appropriate configuration file in the root of the classpath or in the location specified by the following Environment property for Spring: logging.config.

You can force Spring Boot to use a specific logging system using the org.springframework.boot.logging.LoggingSystem system property. The value must be the fully qualified name of the LoggingSystem implementation class. You can also completely disable the Spring Boot logging configuration by using the none value.

Because logging is initialized before creating the ApplicationContext, it is not possible to control logging via the @PropertySources annotation in Spring files with the @Configuration annotation. The only way to change the logging system or disable it completely is through system properties.

Depending on the logging system, the following files are loaded:

Logging system Settings

Logback

logback-spring.xml, logback-spring.groovy, logback.xml, or logback.groovy

Log4j2

log4j2-spring.xml or log4j2.xml

JDK (Java Util Logging)

logging.properties

If possible, we recommend using -spring options for logging configuration (for example, logback-spring.xml , not logback.xml). If standard configuration locations are used, Spring will not be able to fully control log initialization.
There are known quirks with class loading in Java Util Logging that cause startup problems from the "executable jar file". We recommend avoiding this if possible when running from an "executable jar".

To simplify configuration, some other properties are moved from Environment for Spring to system properties, as described in the following table :

Spring Environment System Property Comments

logging.exception-conversion-word

LOG_EXCEPTION_CONVERSION_WORD

The conversion word used when logging exceptions.

logging.file.name

LOG_FILE

If defined, it is used in the default log configuration.

logging.file.path

LOG_PATH

If defined, it is used in the default logging configuration.

logging.pattern.console

CONSOLE_LOG_PATTERN

Log pattern for use with the console (STDOUT).

logging.pattern.dateformat

LOG_DATEFORMAT_PATTERN

Appender pattern for formatting the log date.

logging.charset.console

CONSOLE_LOG_CHARSET

Encoding used for logging log with console output.

logging.pattern.file

FILE_LOG_PATTERN

Log pattern to use in the file (if the LOG_FILE property is activated).

logging.charset.file

FILE_LOG_CHARSET

Encoding used for logging files (if the LOG_FILE property is activated).

logging.pattern.level

LOG_LEVEL_PATTERN

Format used when visualizing the log level (default %5p).

PID

PID

Identifier of the current process (recognized if possible and if it is not already defined as an OS environment variable).

If you use Logback, the following properties are also passed:

Spring Environment System Property Comments

logging.logback.rollingpolicy.file-name-pattern

LOGBACK_ROLLINGPOLICY_FILE_NAME_PATTERN

Template for names of archived log files (by default ${LOG_FILE}.%d{yyyy-MM-dd}.%i.gz).

logging.logback.rollingpolicy.clean-history-on-start

LOGBACK_ROLLINGPOLICY_CLEAN_HISTORY_ON_START

Indicates whether files in the log archive should be cleared at startup.

logging.logback.rollingpolicy.max-file-size

LOGBACK_ROLLINGPOLICY_MAX_FILE_SIZE

Maximum log file size.

logging.logback.rollingpolicy.total-size-cap

LOGBACK_ROLLINGPOLICY_TOTAL_SIZE_CAP

Total size of stored log backups.

logging.logback.rollingpolicy.max-history

LOGBACK_ROLLINGPOLICY_MAX_HISTORY

The maximum number of files in the log archive that need to be stored.

All supported logging systems can access system properties when parsing their configuration files. See examples of default configurations in spring-boot.jar:

If you need to use a placeholder in a logging property, you should stick to Spring Boot syntax rather than the underlying framework syntax. In particular, if you use Logback, you should use : as the delimiter between the property name and its default value, rather than :-.

You can add MDC context and other special content to log lines by overriding only LOG_LEVEL_PATTERN (or logging. pattern.level in Logback). For example, if you use logging.pattern.level=user:%X{user} %5p, then the default logger format contains an MDC entry for "user" if it exists, as shown in the following example .

2019-08-30 12:30:04.031 user:someone INFO 22174 --- [ nio-8080-exec-0] demo.Controller
Handling authenticated request

Logback extensions

Spring Boot contains a number of extensions for Logback that can simplify in-depth configuration. You can use these extensions in the logback-spring.xml configuration file.

Because the standard logback.xml configuration file is loaded too early, extensions cannot be used in it. You must either use logback-spring.xml or define the logging.config property.
Extensions cannot be used with configuration scan from Logback. If you attempt to do this, making changes to the configuration file will result in an error like one of the following being logged:
ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:71 - no applicable action for [springProperty], current ElementPath is [[configuration][springProperty]]
ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:71 - no applicable action for [springProfile], current

Profile-specific configuration

The <springProfile> tag allows you to optionally include or exclude configuration sections based on active Spring profiles. Profile sections are supported anywhere in the <configuration> element. Use the name attribute to specify which profile accepts the configuration. The <springProfile> tag can contain a profile name (for example, staging) or a profile expression. A profile expression allows you to express more complex profile logic (e.g. production & (eu-central | eu-west)). The following listing shows three sample profiles:

<springProfile name="staging">
            <!-- configuration that will be activated if the "staging" profile is active -->
</springProfile>
<springProfile name="dev | staging">
             <!-- the configuration that will be activated if the "dev" or "staging" profile is active -->
</springProfile>
<springProfile name="!production">
             <!-- configuration that will be activated if the "production" profile is active -->
</springProfile>

Environment Properties

The <springProperty> tag allows you to open properties from Environment in Spring for use in Logback. This can be useful if you need to access values from the application.properties file in your Logback configuration. This tag works the same as the standard <property> tag in Logback. However, instead of setting a direct value, you set the source property (from Environment). If you need to store a property outside of the local accessibility scope, you can use the scope attribute. If you need a fallback value (in case the property is not set to Environment), you can use the defaultValue attribute. The following example shows how to expose properties for use in Logback:

<springProperty scope="context" name="fluentHost" source="myapp.fluentd.host"
                defaultValue="localhost"/>
<appender name="FLUENT" class="ch.qos.logback.more.appenders.DataFluentAppender">
    <remoteHost>${fluentHost}</remoteHost>
    ...
</appender>
You need to specify source in the kebab register (for example, my.property-name). However, properties can be added to Environment using loose rules.