Spring Boot
Log Messages
Logging to File
Java Development
Spring Framework

How to write log messages to file using Spring Boot?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Writing logs to files in Spring Boot is easy to enable, but production-ready logging requires path strategy, rotation policy, and structured message design. Relying only on console output makes incident analysis harder after process restarts. A clear file logging setup improves observability and operational debugging.

Core Sections

Basic File Logging Configuration

Spring Boot supports file logging with simple properties.

properties
1# application.properties
2logging.file.name=logs/app.log
3logging.level.root=INFO
4logging.level.com.example=DEBUG

This creates and writes to the configured log file path. If directories do not exist, ensure runtime user permissions allow creation.

Use Pattern Configuration for Readable Logs

Customize log line format for timestamps, thread names, and logger classes.

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

Readable patterns reduce troubleshooting time during outages.

Configure Rotation with Logback

For robust rollover policy, provide a logback-spring.xml configuration.

xml
1<configuration>
2  <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
3    <file>logs/app.log</file>
4    <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
5      <fileNamePattern>logs/app.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
6      <maxFileSize>20MB</maxFileSize>
7      <maxHistory>14</maxHistory>
8      <totalSizeCap>2GB</totalSizeCap>
9    </rollingPolicy>
10    <encoder>
11      <pattern>%d %-5level [%thread] %logger - %msg%n</pattern>
12    </encoder>
13  </appender>
14
15  <root level="INFO">
16    <appender-ref ref="FILE" />
17  </root>
18</configuration>

Rotation prevents unbounded disk usage while keeping recent history.

Log from Application Code with Context

Use SLF4J logger fields and include contextual identifiers in messages.

java
1import org.slf4j.Logger;
2import org.slf4j.LoggerFactory;
3
4public class PaymentService {
5    private static final Logger log = LoggerFactory.getLogger(PaymentService.class);
6
7    public void process(String paymentId) {
8        log.info("Processing payment id={}", paymentId);
9        try {
10            // business logic
11            log.debug("Payment validation passed id={}", paymentId);
12        } catch (Exception ex) {
13            log.error("Payment failed id={}", paymentId, ex);
14            throw ex;
15        }
16    }
17}

Structured placeholder logging is preferred over string concatenation.

Environment-specific Configuration

In development, console logging may be enough, while production requires rolling files or external log shipping. Use profile-specific properties to separate behavior.

properties
# application-prod.properties
logging.file.name=/var/log/myapp/app.log
logging.level.root=INFO

This keeps local setup simple and production setup stable.

Operational Best Practices

Store logs on persistent volumes in containerized deployments, or forward logs to centralized platforms. If file logs are required for compliance, document retention windows and secure file permissions.

Include startup logs that print active profile, app version, and build hash. These details improve traceability when multiple deployments exist.

Structured Logging and Correlation IDs

Plain text logs are helpful, but structured logs make search and correlation much easier. Add correlation IDs so one request path can be tracked across services and asynchronous steps.

java
1import org.slf4j.MDC;
2
3public void withRequestContext(String requestId) {
4    try {
5        MDC.put("requestId", requestId);
6        log.info("Request started");
7    } finally {
8        MDC.remove("requestId");
9    }
10}

Then include MDC fields in log pattern configuration. This improves incident triage by grouping related events.

Testing Logging Configuration

Logging setups should be validated like other infrastructure code. Add startup checks in integration tests to assert expected appenders and active log levels under each profile. During release verification, confirm files rotate and permissions remain correct under runtime user accounts.

In container orchestration environments, decide clearly whether logs are consumed from files or standard output. Hybrid setups are possible but should be intentional and documented.

For audit-sensitive domains, pair file logging with checksum or immutable storage strategies so critical events remain tamper-evident. Logging policy should align with legal and compliance obligations, not only engineering preferences.

Common Pitfalls

  • Writing logs only to ephemeral container files without persistence.
  • Using verbose DEBUG levels globally in production.
  • Missing rotation policies and filling disk space.
  • Logging sensitive data such as secrets or personal identifiers.
  • Using inconsistent log formats across services.

Summary

  • Enable Spring Boot file logging via properties or Logback configuration.
  • Use clear patterns and rolling policies for maintainable log files.
  • Log contextual IDs with structured placeholders.
  • Separate development and production logging behavior by profile.
  • Treat retention, security, and centralization as part of logging design.

Course illustration
Course illustration

All Rights Reserved.