Spring Boot Logging

Complete beginner-friendly chapter — from simple console logs to structured JSON, Logback and Log4j2 customization
Source basis: This chapter follows the current Spring Boot 4.1.1 official Logging documentation and turns its concepts into a practical learning chapter. The goal is understanding and application, not copying the documentation.

1. The Big Idea

Logging means recording what your application is doing while it runs.

For example, when a Spring Boot application starts, you may see:

2026-08-17T10:51:28.508Z INFO ... Starting MyApplication
2026-08-17T10:51:35.286Z INFO ... Started MyApplication

Logs help you answer questions such as:

  • Did the application start successfully?
  • Which request or component failed?
  • Which package is producing too much output?
  • What happened immediately before an exception?
  • What is happening in production?
Remember: Logging is mainly a diagnostic and operational tool. Good logs help developers and operators understand an application without stopping it or attaching a debugger.

2. What Spring Boot Uses for Logging

Spring Boot uses Commons Logging internally while leaving the underlying logging implementation open. Spring Boot provides default configurations for Java Util Logging, Log4j2 and Logback.

When you use Spring Boot starters, Logback is the default logging implementation. Spring Boot also provides routing so libraries using JUL, Commons Logging, Log4J or SLF4J can work together.

TermSimple meaning
Commons LoggingLogging abstraction used by Spring Boot internally.
SLF4JCommon logging API frequently used by Java applications.
LogbackDefault implementation when using Spring Boot starters.
Log4j2Another popular logging implementation.
JULJava Util Logging, provided by the JDK.
Beginner advice: You normally do not need to replace the default logging dependencies just to start logging. Spring Boot defaults are enough for most applications.

3. Anatomy of a Spring Boot Log Line

A default log entry contains several useful pieces of information.

2026-08-17T10:51:28.508Z INFO 11390 --- [myapp] [main] com.example.MyApplication : Starting MyApplication
PartMeaning
Date and timeWhen the event happened.
Log levelERROR, WARN, INFO, DEBUG or TRACE.
Process IDID of the running JVM process.
Application nameIncluded when spring.application.name is set.
Application groupIncluded when spring.application.group is set.
ThreadThread that produced the message.
Logger nameUsually the source class/package, often abbreviated.
MessageThe actual information being logged.

Logback does not have a separate FATAL level; Spring Boot maps it to ERROR.

4. Log Levels

Think of log levels as a volume control for diagnostic information.

LevelMeaningTypical use
TRACEExtremely detailed information.Deep troubleshooting.
DEBUGDetailed developer information.Development and debugging.
INFONormal application events.Startup, major business flow.
WARNSomething unexpected or potentially problematic.Deprecated behavior, recoverable issue.
ERRORAn operation failed.Exceptions and serious failures.
FATALSupported as a configurable level, but Logback maps it to ERROR.Framework-specific semantics.
OFFDisable logging for the selected logger.Very targeted suppression.
TRACE = deepest detailDEBUG = developer detailINFO = normal flowWARN = concernERROR = failure

5. Console Logging

By default, Spring Boot writes logs to the console. ERROR, WARN and INFO messages are logged by default.

Enable Debug Mode

java -jar myapp.jar --debug

Or:

debug=true

Debug mode increases detail for a selection of core loggers such as the embedded container, Hibernate and Spring Boot. It does not mean that every application logger is automatically set to DEBUG.

Enable Trace Mode

java -jar myapp.jar --trace

Or:

trace=true

Trace mode enables trace logging for selected core areas, including the embedded container, Hibernate schema generation and the Spring portfolio.

Disable Console Logging

logging.console.enabled=false

6. Color-Coded Console Output

If the terminal supports ANSI output, Spring Boot can use colors to make logs easier to read.

spring.output.ansi.enabled=always

Spring Boot's %clr conversion word can color output based on the log level.

%clr(%5p)
LevelDefault color mapping
FATALRed
ERRORRed
WARNYellow
INFOGreen
DEBUGGreen
TRACEGreen

You can specify a color and style:

%clr(%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}){yellow,bold}

7. Writing Logs to a File

By default, Spring Boot logs to the console only. To create log files, use logging.file.name or logging.file.path.

ConfigurationResult
Neither propertyConsole only.
logging.file.name=my.logWrites to the specified file.
logging.file.path=/var/logWrites spring.log into that directory.
Both setlogging.file.name wins; path is ignored.
logging.file.name=logs/application.log

or:

logging.file.path=logs
Default rotation: Log files rotate when they reach 10 MB. By default, ERROR, WARN and INFO messages are written.

8. File Rotation

Log rotation prevents one log file from growing forever.

Logback Rotation Properties

PropertyPurpose
logging.logback.rollingpolicy.file-name-patternArchive filename pattern.
logging.logback.rollingpolicy.clean-history-on-startClean archives when the application starts.
logging.logback.rollingpolicy.max-file-sizeMaximum size before archiving.
logging.logback.rollingpolicy.total-size-capTotal space allowed for archives.
logging.logback.rollingpolicy.max-historyMaximum archive count; default is 7.
logging.file.name=logs/app.log
logging.logback.rollingpolicy.max-file-size=20MB
logging.logback.rollingpolicy.max-history=14
logging.logback.rollingpolicy.total-size-cap=500MB

Log4j2 Rotation Properties

PropertyPurpose
logging.log4j2.rollingpolicy.file-name-patternArchive filename pattern.
logging.log4j2.rollingpolicy.max-file-sizeMaximum file size; default 10MB.
logging.log4j2.rollingpolicy.max-historyMaximum archives; default 7.
logging.log4j2.rollingpolicy.strategyRolling strategy; default is size.
logging.log4j2.rollingpolicy.cronCron expression when cron strategy is used.
logging.log4j2.rollingpolicy.time-intervalTime-based triggering interval.
logging.log4j2.rollingpolicy.time-modulateWhether to align the next rollover with the interval.

9. Setting Logger Levels

The most useful Spring Boot logging configuration is:

logging.level.<logger-name>=<level>

Example:

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"
Think of a logger as a filter. Setting org.springframework.web to DEBUG affects that logger/package while leaving unrelated loggers at their configured levels.

Environment Variables

LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_WEB=DEBUG
Important: Environment-variable relaxed binding converts names to lowercase, so this approach works for package-level logging but cannot configure an individual class logger reliably. For an individual class, Spring Boot's SPRING_APPLICATION_JSON can be used.

10. Log Groups

Sometimes you want to control several related loggers together. A logging group gives them one convenient name.

logging.group.tomcat=org.apache.catalina,org.apache.coyote,org.apache.tomcat

logging.level.tomcat=trace

YAML:

logging:
  group:
    tomcat: "org.apache.catalina,org.apache.coyote,org.apache.tomcat"
  level:
    tomcat: "trace"
Built-in groupIncludes
webSpring core codec, HTTP, web, Actuator web endpoint and servlet initialization loggers.
sqlSpring JDBC, Hibernate SQL and jOOQ LoggerListener.

11. Shutdown Hook

Spring Boot provides a shutdown hook to clean up logging resources when the JVM exits. It is registered automatically unless the application is deployed as a WAR.

Disable it when the application's context hierarchy or logging setup requires direct control:

logging.register-shutdown-hook=false

12. Custom Log Configuration

You can provide a logging configuration file or specify its location with:

logging.config=classpath:my-logback.xml

Spring Boot can use different logging systems depending on the libraries available on the classpath.

Logging systemConfiguration files
Logbacklogback-spring.xml, logback-spring.groovy, logback.xml, logback.groovy
Log4j2log4j2-spring.xml, log4j2.xml
JULlogging.properties
Best practice from the docs: When possible, prefer the -spring variants such as logback-spring.xml. They allow Spring Boot to have more control over initialization.
Important: Logging is initialized before the ApplicationContext is created. Therefore, you cannot use @PropertySource inside configuration to control the logging system during initialization.

13. Force or Disable Spring Boot's Logging System

The system property org.springframework.boot.logging.LoggingSystem can force a particular implementation.

-Dorg.springframework.boot.logging.LoggingSystem=com.example.MyLoggingSystem

It can also disable Spring Boot logging configuration:

-Dorg.springframework.boot.logging.LoggingSystem=none

14. Properties Passed to the Logging System

Spring Boot transfers selected Environment properties into System properties so the underlying logging configuration can use them.

Spring propertySystem property
logging.file.nameLOG_FILE
logging.file.pathLOG_PATH
logging.pattern.consoleCONSOLE_LOG_PATTERN
logging.pattern.fileFILE_LOG_PATTERN
logging.pattern.dateformatLOG_DATEFORMAT_PATTERN
logging.pattern.levelLOG_LEVEL_PATTERN
logging.charset.consoleCONSOLE_LOG_CHARSET
logging.threshold.consoleCONSOLE_LOG_THRESHOLD
logging.structured.format.consoleCONSOLE_LOG_STRUCTURED_FORMAT
logging.structured.format.fileFILE_LOG_STRUCTURED_FORMAT

For Logback, Spring Boot also transfers rolling-policy properties into corresponding LOGBACK_... system properties.

15. Logging Patterns and MDC

You can customize the level portion of the log output using logging.pattern.level.

logging.pattern.level=user:%X{user} %5p

This can include an MDC value such as a user identifier when that value exists.

MDC idea: MDC (Mapped Diagnostic Context) is useful when you want extra contextual information—such as a user, request or correlation value—to appear with log messages.

16. Structured Logging

Structured logging means writing logs in a predictable, machine-readable structure instead of relying only on human-oriented text.

Spring Boot provides structured logging support for:

ECSGELFLogstash

Enable it for console:

logging.structured.format.console=ecs

Or file:

logging.structured.format.file=ecs

You can configure both:

logging.structured.format.console=ecs
logging.structured.format.file=ecs
Why structured logs? Humans can read normal logs, but machines can much more easily search, filter, aggregate and analyze predictable JSON fields.

17. Elastic Common Schema (ECS)

ECS is a JSON-based logging format.

logging.structured.format.console=ecs
logging.structured.format.file=ecs

A typical ECS record contains fields for timestamp, level, logger, process, service and message.

ECS also includes key-value pairs stored in MDC. SLF4J's fluent logging API can add key-value pairs using addKeyValue.

Customize ECS Service Information

logging.structured.ecs.service.name=MyService
logging.structured.ecs.service.version=1
logging.structured.ecs.service.environment=Production
logging.structured.ecs.service.node-name=Primary

If not specified, the ECS service name defaults to spring.application.name, and service version defaults to spring.application.version.

18. Graylog Extended Log Format (GELF)

GELF is a JSON-based format intended for the Graylog log analytics platform.

logging.structured.format.console=gelf
logging.structured.format.file=gelf

Some GELF fields can be customized:

logging.structured.gelf.host=MyService
logging.structured.gelf.service.version=1

The GELF host defaults to spring.application.name when not specified, and service version defaults to spring.application.version.

19. Logstash JSON Format

Logstash JSON is another structured JSON format.

logging.structured.format.console=logstash
logging.structured.format.file=logstash

Like the other structured formats, MDC key-value pairs are included. SLF4J markers can also appear as a tags string array.

20. Customizing Structured JSON

Spring Boot provides properties for small changes to generated structured JSON.

PropertyPurpose
logging.structured.json.include / excludeInclude or filter specific JSON paths.
logging.structured.json.renameRename a JSON member.
logging.structured.json.addAdd additional JSON members.

Example:

logging.structured.json.exclude=log.level
logging.structured.json.rename.process.id=procid
logging.structured.json.add.corpname=mycorp

For more advanced customization, implement StructuredLoggingJsonMembersCustomizer.

21. Customizing Structured Stack Traces

Structured logs include complete exception stack traces by default. For large systems, this can increase ingestion and processing costs.

PropertyPurpose
logging.structured.json.stacktrace.rootUse first or last for the root item.
logging.structured.json.stacktrace.max-lengthMaximum printed length.
logging.structured.json.stacktrace.max-throwable-depthMaximum number of frames.
logging.structured.json.stacktrace.include-common-framesInclude or remove common frames.
logging.structured.json.stacktrace.include-hashesInclude a stack-trace hash.
logging.structured.json.stacktrace.root=first
logging.structured.json.stacktrace.max-length=1024
logging.structured.json.stacktrace.include-common-frames=true
logging.structured.json.stacktrace.include-hashes=true

For full control, configure logging.structured.json.stacktrace.printer with a StackTracePrinter implementation, or use logging-system for regular logging-system stack trace output.

22. Creating Your Own Structured Format

Spring Boot's structured logging support is extensible. Implement StructuredLogFormatter.

import ch.qos.logback.classic.spi.ILoggingEvent;
import org.springframework.boot.logging.structured.StructuredLogFormatter;

class MyCustomFormat implements StructuredLogFormatter<ILoggingEvent> {

    @Override
    public String format(ILoggingEvent event) {
        return "time=" + event.getInstant()
            + " level=" + event.getLevel()
            + " message=" + event.getMessage() + "\n";
    }
}

Then configure the console or file format with the fully qualified class name of your implementation.

logging.structured.format.console=com.example.MyCustomFormat
The custom formatter does not have to return JSON. It can return another format appropriate for your system.

23. Logback Extensions

Spring Boot provides Logback extensions for advanced configuration. These are intended for logback-spring.xml.

Important: Standard logback.xml is loaded too early for these Spring Boot extensions. Use logback-spring.xml or specify a configuration through logging.config.

Profile-Specific Logback Configuration

<springProfile name="staging">
    <!-- staging configuration -->
</springProfile>

<springProfile name="dev | staging">
    <!-- dev OR staging -->
</springProfile>

<springProfile name="!production">
    <!-- when production is not active -->
</springProfile>

Profile expressions can also be more complex, such as:

production & (eu-central | eu-west)

Using Spring Environment Properties

The <springProperty> tag exposes Spring Environment values to 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>

The source should be written in kebab case, such as my.property-name.

24. Log4j2 Extensions

Spring Boot also provides extensions for Log4j2 through log4j2-spring.xml.

Important: Standard log4j2.xml loads too early for Spring Boot extensions. Use log4j2-spring.xml or configure logging.config.

Profile-Specific Configuration

<SpringProfile name="staging">
    <!-- staging configuration -->
</SpringProfile>

<SpringProfile name="dev | staging">
    <!-- dev OR staging -->
</SpringProfile>

<SpringProfile name="!production">
    <!-- not production -->
</SpringProfile>

Spring Environment Lookup

Log4j2 can use spring:-prefixed lookups:

<Properties>
    <Property name="applicationName">
        ${spring:spring.application.name}
    </Property>
    <Property name="applicationGroup">
        ${spring:spring.application.group}
    </Property>
</Properties>

Lookup keys should be specified in kebab case.

25. A Practical Spring Boot Logging Setup

A simple production-oriented starting point might look like this:

spring.application.name=order-service

# Normal application logging
logging.level.root=INFO

# More detail for your application
logging.level.com.example.orders=DEBUG

# Keep framework noise lower
logging.level.org.hibernate=WARN

# Write to a file
logging.file.name=logs/order-service.log

# Rotate logs
logging.logback.rollingpolicy.max-file-size=20MB
logging.logback.rollingpolicy.max-history=14
logging.logback.rollingpolicy.total-size-cap=500MB
Mental model:
ApplicationLoggerLevel filterConsole/FileRotationStructured JSONLog platform

26. Common Mistakes

  1. Setting DEBUG globally in production. This can create excessive noise and storage/processing costs.
  2. Confusing --debug with all DEBUG logging. Spring Boot debug mode only enables more detail for selected core loggers.
  3. Using both file properties incorrectly. When both logging.file.name and logging.file.path are set, the name wins.
  4. Putting Spring Boot Logback extensions in logback.xml. Use logback-spring.xml.
  5. Assuming @PropertySource controls early logging. Logging initializes before the ApplicationContext.
  6. Keeping unlimited log files. Configure rotation and retention.
  7. Using human-only logs for large distributed systems. Consider structured logging.
  8. Logging sensitive information. Avoid passwords, tokens, secrets and unnecessary personal data.

27. Best Practices

  • Use INFO for important normal application events.
  • Use DEBUG for developer troubleshooting.
  • Use WARN for recoverable or suspicious conditions.
  • Use ERROR when an operation fails.
  • Keep production logging useful rather than extremely verbose.
  • Use file rotation when writing logs to disk.
  • Use logger/package-specific levels instead of global DEBUG where possible.
  • Use logging groups when several related loggers need the same level.
  • Prefer -spring logging configuration files for Spring Boot extensions.
  • Consider structured JSON logs when logs are consumed by centralized observability systems.
  • Do not put secrets or unnecessary sensitive data in logs.

28. Interview Questions

Q1. What is the default logging implementation in Spring Boot?

Logback when using Spring Boot starters.

Q2. What is the difference between DEBUG mode and setting every logger to DEBUG?

Spring Boot debug mode increases detail for selected core loggers. It does not automatically make every application logger DEBUG.

Q3. How do you change the log level for a package?
logging.level.com.example=DEBUG
Q4. How do you write Spring Boot logs to a file?
logging.file.name=logs/application.log

or use logging.file.path for a directory.

Q5. What happens if logging.file.name and logging.file.path are both configured?

logging.file.name is used and logging.file.path is ignored.

Q6. What is a logging group?

A named collection of loggers that can be configured together.

Q7. Why use logback-spring.xml instead of logback.xml?

Spring Boot extensions require the Spring-aware configuration file because standard logback.xml is loaded too early.

Q8. What is structured logging?

Logging in a predictable, often machine-readable format such as JSON.

Q9. Which structured formats does Spring Boot support out of the box?

ECS, GELF and Logstash.

Q10. When is structured logging useful?

Especially when logs are collected, searched and analyzed by centralized observability/log analytics systems.

29. Practice Exercises

  1. Set your application's root logger to WARN.
  2. Set your own package to DEBUG.
  3. Configure logs to be written to logs/app.log.
  4. Configure Logback to keep 14 archive files.
  5. Create a custom tomcat logging group.
  6. Enable ECS structured logging on the console.
  7. Create a profile-specific Logback section for dev.
  8. Try adding an MDC value to the log-level pattern.
  9. Explain why logback-spring.xml is preferred for Spring Boot extensions.
  10. Design a logging configuration for a production REST API and explain every setting.

30. Quick Cheat Sheet

GoalConfiguration
Root levellogging.level.root=INFO
Package levellogging.level.com.example=DEBUG
File logginglogging.file.name=logs/app.log
Directory logginglogging.file.path=logs
Disable consolelogging.console.enabled=false
Debug mode--debug or debug=true
Trace mode--trace or trace=true
Logging grouplogging.group.name=logger1,logger2
Group levellogging.level.name=TRACE
Shutdown hook offlogging.register-shutdown-hook=false
Custom configlogging.config=...
ECSlogging.structured.format.console=ecs
GELFlogging.structured.format.console=gelf
Logstashlogging.structured.format.console=logstash

31. Memory Map

Spring Boot Logging →

Default Logback → Log levels → Console → Files → Rotation → Logger levels → Groups → Shutdown hook → Custom configuration → Structured logging → ECS / GELF / Logstash → JSON customization → Stack traces → Logback extensions → Log4j2 extensions

32. Final Takeaway

Spring Boot gives you useful logging defaults so you can start without complicated configuration. As the application grows, you can control where logs go, which levels are emitted, how files rotate, which loggers are grouped, and how logs are structured for machines.

The most important practical progression is:

1. Understand levels2. Configure package levels3. Add file logging if needed4. Configure rotation5. Customize Logback/Log4j26. Adopt structured logs when useful