Master Spring Boot 3.x Logging: Logback Integration, Advanced Config & Best Practices

This guide explains how Spring Boot 3.x uses Logback by default, shows basic property‑based setup, advanced logback‑spring.xml configurations, profile‑specific logging, SQL tracing with Hibernate, MyBatis, p6spy and datasource‑proxy, plus MDC tracing, async logging, alerting and production best practices.

Ray's Galactic Tech
Ray's Galactic Tech
Ray's Galactic Tech
Master Spring Boot 3.x Logging: Logback Integration, Advanced Config & Best Practices

Basic logging configuration (application.properties / application.yml)

# Log level
logging.level.root=INFO
logging.level.org.springframework=WARN
logging.level.com.myapp=DEBUG

# Log file
logging.file.name=app.log
logging.file.path=/var/log

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

Advanced Logback configuration (logback-spring.xml)

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="30 seconds">
  <!-- Environment variables -->
  <springProperty scope="context" name="APP_NAME" source="spring.application.name" defaultValue="spring-boot-app"/>
  <springProperty scope="context" name="LOG_PATH" source="logging.file.path" defaultValue="./logs"/>
  <springProperty scope="context" name="LOG_LEVEL" source="logging.level.root" defaultValue="INFO"/>

  <!-- Console appender -->
  <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
      <charset>UTF-8</charset>
    </encoder>
  </appender>

  <!-- Rolling file appender -->
  <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${LOG_PATH}/${APP_NAME}.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
      <fileNamePattern>${LOG_PATH}/${APP_NAME}-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
      <maxFileSize>50MB</maxFileSize>
      <maxHistory>30</maxHistory>
      <totalSizeCap>1GB</totalSizeCap>
    </rollingPolicy>
    <encoder>
      <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
      <charset>UTF-8</charset>
    </encoder>
  </appender>

  <!-- JSON file appender (for ELK/EFK) -->
  <appender name="JSON_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${LOG_PATH}/${APP_NAME}.json</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
      <fileNamePattern>${LOG_PATH}/${APP_NAME}-%d{yyyy-MM-dd}.%i.json</fileNamePattern>
      <maxFileSize>50MB</maxFileSize>
      <maxHistory>30</maxHistory>
      <totalSizeCap>1GB</totalSizeCap>
    </rollingPolicy>
    <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder"/>
  </appender>

  <!-- Root logger -->
  <root level="${LOG_LEVEL}">
    <appender-ref ref="CONSOLE"/>
    <appender-ref ref="FILE"/>
  </root>

  <!-- Package‑specific loggers -->
  <logger name="org.springframework" level="WARN"/>
  <logger name="com.myapp" level="DEBUG"/>
</configuration>

JSON encoder dependency

<dependency>
  <groupId>net.logstash.logback</groupId>
  <artifactId>logstash-logback-encoder</artifactId>
  <version>7.4</version>
</dependency>

Profile‑based configuration

<springProfile name="dev">
  <root level="DEBUG">
    <appender-ref ref="CONSOLE"/>
  </root>
</springProfile>

<springProfile name="prod">
  <root level="INFO">
    <appender-ref ref="FILE"/>
    <appender-ref ref="JSON_FILE"/>
    <appender-ref ref="ASYNC_FILE"/>
  </root>
</springProfile>

SQL logging options

Hibernate/JPA: enable spring.jpa.show-sql=true and spring.jpa.properties.hibernate.format_sql=true, then set logger levels org.hibernate.SQL=DEBUG and org.hibernate.type.descriptor.sql.BasicBinder=TRACE.

MyBatis: set logging.level.com.myapp.mapper=DEBUG.

Direct Logback logger entries for org.hibernate.SQL, org.hibernate.type.descriptor.sql, org.mybatis, java.sql and javax.sql as needed.

p6spy integration (recommended)

<dependency>
  <groupId>com.github.gavlyukovskiy</groupId>
  <artifactId>p6spy-spring-boot-starter</artifactId>
  <version>1.9.0</version>
</dependency>
# application.properties
spring.datasource.url=jdbc:p6spy:mysql://localhost:3306/mydb
logging.level.p6spy=INFO

# spy.properties
appender=com.p6spy.engine.spy.appender.Slf4JLogger
logMessageFormat=com.p6spy.engine.spy.appender.CustomLineFormat
customLogMessageFormat=%(executionTime)ms | %(category) | connection %(connectionId) | %(sqlSingleLine)
executionThreshold=500
excludecategories=info,debug,result,batch

Datasource‑Proxy alternative

<dependency>
  <groupId>net.ttddyy</groupId>
  <artifactId>datasource-proxy</artifactId>
  <version>1.8</version>
</dependency>
@Bean
public DataSource dataSource(DataSource originalDataSource) {
    return ProxyDataSourceBuilder.create(originalDataSource)
        .name("ProxyDS")
        .countQuery()
        .logQueryBySlf4j(SLF4JLogLevel.INFO)
        .multiline()
        .jsonFormat()
        .build();
}

Advanced features

MDC tracing : inject a trace identifier into the logging context for request‑level correlation.

MDC.put("traceId", UUID.randomUUID().toString());
try {
    log.info("业务处理开始");
} finally {
    MDC.clear();
}

Async appender : use ch.qos.logback.classic.AsyncAppender to avoid blocking in high‑throughput scenarios.

<appender name="ASYNC_FILE" class="ch.qos.logback.classic.AsyncAppender">
    <queueSize>1024</queueSize>
    <discardingThreshold>20</discardingThreshold>
    <includeCallerData>false</includeCallerData>
    <appender-ref ref="FILE"/>
</appender>

Sentry alerting : forward ERROR logs to Sentry for monitoring.

<dependency>
  <groupId>io.sentry</groupId>
  <artifactId>sentry-logback</artifactId>
  <version>6.25.0</version>
</dependency>

<appender name="SENTRY" class="io.sentry.logback.SentryAppender">
    <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
        <level>ERROR</level>
    </filter>
</appender>

ELK/EFK pipelines : emit JSON logs (via the JSON_FILE appender) and ship them with Filebeat or Fluentd to Elasticsearch for analysis in Kibana or Graylog.

Best‑practice recommendations

Development

Enable colored console logs for quick debugging.

Use p6spy to capture full SQL statements.

Add TRACE logs for critical business flows.

Testing

Activate slow‑query statistics.

Use JSON logs to simulate production log collection.

Production

Log at INFO level or higher.

Employ async logging to prevent request latency.

Prefer JSON format for ELK/EFK compatibility.

Implement audit logs for key operations.

Configure slow‑SQL alerts to avoid excessive log volume.

Logging diagram
Logging diagram
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaConfigurationloggingSpring Bootlogback
Ray's Galactic Tech
Written by

Ray's Galactic Tech

Practice together, never alone. We cover programming languages, development tools, learning methods, and pitfall notes. We simplify complex topics, guiding you from beginner to advanced. Weekly practical content—let's grow together!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.