Skip to content
Spring Boot Logging: Initialization Order & Config Priority Explained

Spring Boot Logging: Initialization Order & Config Priority Explained

This article dissects Spring Boot's logging system initialization sequence, the two-phase LoggingSystem setup, and the four-tier configuration priority chain from explicit logging.config down to application.yml logging.* properties, with source-code walkthroughs and practical logback-spring.xml examples.

Java Tech Workshop
Java Tech Workshop
Java Tech Workshop

How Spring Boot Logging Connects

Three-Layer Architecture

Spring Boot logging is structured in three layers:

Abstraction layer : SLF4J provides a unified API ( LoggerFactory.getLogger).

Implementation layer : Actual logging output — Logback (default), Log4j2, or JUL (java.util.logging).

Bridging layer : Redirects other frameworks' logs to SLF4J via jul-to-slf4j, jcl-over-slf4j, log4j-over-slf4j.

The default spring-boot-starter-logging pulls in logback-classic, slf4j-api, jul-to-slf4j, jcl-over-slf4j, and log4j-over-slf4j so all third-party logs converge.

Switching Implementations

To use Log4j2, exclude spring-boot-starter-logging and add spring-boot-starter-log4j2:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
  <exclusions>
    <exclusion>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-logging</artifactId>
    </exclusion>
  </exclusions>
</dependency>

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

Initialization Timing

Why Early Initialization?

Application code and container refresh both emit logs; if logging initializes after business code, early startup logs are lost. Spring Boot prepares the logging system before context refresh.

Startup Sequence

JVM startup
  ↓
SpringApplication.run()
  ↓
① Prepare Environment (read application.yml, env vars)
  ↓
② Publish ApplicationEnvironmentPreparedEvent
  ↓
③ LoggingApplicationListener initializes LoggingSystem
  ↓
④ Create & refresh ApplicationContext (bean registration, DI, startup)
  ↓
⑤ Application code logs (logging system already ready)
  ↓
ContextClosedEvent → shut down logging system

Two Initialization Phases

LoggingApplicationListener

handles logging in two steps:

beforeInitialize (preparation): Called when environment is ready; selects the LoggingSystem implementation; basic setup to avoid early log loss.

initialize (full initialization): Runs before/after context preparation; loads config files, applies logging.* properties from Environment; completes actual log output configuration.

Why Very Early Logs May Be Missing

Logs from JVM startup parameters and class loading occur before SpringApplication runs; they use the logging implementation's native defaults. For extreme early diagnostics, use JVM flags like -Ddebug.

Key Listener Code

public class LoggingApplicationListener
    implements ApplicationListener<ApplicationEvent>, Ordered {

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationEnvironmentPreparedEvent) {
            // Environment ready: beforeInitialize + initial load
            initialize(environment, ...);
        }
        if (event instanceof ApplicationPreparedEvent) {
            // Context prepared: re-apply logging.* properties
            setLogLevel(environment);
        }
        if (event instanceof ContextClosedEvent) {
            // Shutdown: stop logging system
            loggingSystem.shutDown();
        }
    }
}

Configuration Loading Order

Four configuration sources, highest to lowest priority:

① logging.config explicit file (highest)
    ↓
② Classpath convention files
    logback-spring.xml / log4j2-spring.xml (Spring extensions)
    logback.xml / log4j2.xml (standard framework configs)
    ↓
③ Spring Boot built-in defaults (fallback when no file found)
    ↓
④ application.yml / properties logging.* properties (applied after initialization)

Explicit Config: logging.config

logging:
  config: classpath:logback-prod.xml

When set, Spring Boot uses this file exclusively and skips convention lookup.

Convention Naming: -spring vs Standard Suffix

logback-spring.xml

— Spring Boot recommended ; supports <springProfile>,

<springProperty>
logback.xml

— Logback standard location; loaded earlier by framework; no Spring extensions log4j2-spring.xml — Log4j2 Spring extension version log4j2.xml — Log4j2 standard version -spring files are loaded by Spring Boot's LoggingSystem and can read Environment properties and profile-specific config; standard files may be picked up earlier by the framework itself — a common cause of "config not taking effect".

Built-in Defaults

If no convention file and no logging.config, Spring Boot uses internal defaults: console output, default pattern, DEBUG/INFO levels by package.

YML logging.* Properties

Applied after logging system initialization; common keys:

logging:
  level:
    root: info
    com.demo.order: debug
  file:
    name: logs/order-app.log
  pattern:
    console: "%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n"
  group:
    business: com.demo.order,com.demo.pay

Override Rules

Config file internals define appenders, format, rolling strategy.

YML logging.level adjusts levels after file config — runtime property override. logging.config file outranks convention files.

Avoid conflicting levels/paths across sources; verify which file actually loaded when troubleshooting.

Core Source Code

LoggingSystem Abstraction

public abstract class LoggingSystem {
    public abstract void beforeInitialize(LoggingInitializationContext context);
    public abstract void initialize(LoggingInitializationContext context,
                                    String configLocation, LogFile logFile);
    public abstract void setLogLevel(String loggerName, LogLevel level);
    public abstract void shutDown();
    public abstract LoggerSystem getLoggerSystem();
}

Three Implementations

LogbackLoggingSystem

— Logback (default) Log4J2LoggingSystem — Log4j2 JavaLoggingSystem — JUL (java.util.logging)

Detection Process

LoggingSystemFactory

probes classpath in order:

LoggingSystem.get(classLoader)
    ↓
Probe sequentially:
  Logback class present → LogbackLoggingSystem
  else Log4j2 class present → Log4J2LoggingSystem
  else fallback → JavaLoggingSystem

Config File Location (Logback Example)

// LogbackLoggingSystem simplified logic
protected void initialize(LoggingInitializationContext context,
                          String configLocation, LogFile logFile) {
    if (configLocation != null) {
        // ① Use explicit file
        loadConfiguration(context, configLocation);
    } else {
        // ② Find convention: logback-spring.xml → logback.xml
        String location = getStandardConfigLocation();
        if (location != null) {
            loadConfiguration(context, location);
        } else {
            // ③ Built-in default config
            applyDefaultConfiguration(context, logFile);
        }
    }
}

Level Application

setLogLevel

writes YML logging.level.* back into the logging implementation:

private void setLogLevel(ConfigurableEnvironment environment) {
    Binder binder = Binder.get(environment);
    Map<String, LogLevel> levels = binder.bind("logging.level",
            Bindable.mapOf(String.class, LogLevel.class));
    levels.forEach((name, level) -
            loggingSystem.setLogLevel(name, level));
}

Practical Configuration

Standard logback-spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="30 seconds">

    <!-- Read property from Environment -->
    <springProperty name="APP_NAME" source="spring.application.name"
                    defaultValue="order-app"/>

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

    <!-- File appender, daily rolling -->
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>logs/${APP_NAME}.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>logs/${APP_NAME}.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <maxFileSize>100MB</maxFileSize>
            <maxHistory>30</maxHistory>
        </rollingPolicy>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <!-- Profile-specific: dev only console -->
    <springProfile name="dev">
        <root level="INFO">
            <appender-ref ref="CONSOLE"/>
        </root>
    </springProfile>

    <springProfile name="prod">
        <root level="INFO">
            <appender-ref ref="CONSOLE"/>
            <appender-ref ref="FILE"/>
        </root>
    </springProfile>
</configuration>

YML Package-Level Adjustment

logging:
  level:
    root: info
    com.demo.order: debug
    org.springframework.web: info
  file:
    name: logs/order-app.log

Log Grouping

Group related packages for unified level control:

logging:
  group:
    business: com.demo.order,com.demo.pay,com.demo.user
  level:
    business: debug

Division of Labor: Config File vs YML

File owns structure : appenders, rolling policies, format, profile branches.

YML owns tuning : levels, output file paths.

Environment differences (dev/prod) managed via <springProfile> or multiple YML files.

Understanding logging initialization, LoggingSystem, and config priority is a high-frequency topic for Spring Boot advanced interviews and production troubleshooting. Mastering the startup chain enables precise diagnosis of "missing logs", "config not effective", and "framework log crosstalk".

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.

ConfigurationSource Code AnalysisLoggingSpring BootLogbackSLF4JInitializationLog4j2
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.