CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-springframework-boot--spring-boot-starter-logging

Starter for logging using Logback, providing default logging configuration for Spring Boot applications

Pending
Overview
Eval results
Files

Spring Boot Starter Logging

Spring Boot Starter Logging provides the default logging configuration for Spring Boot applications. It serves as a dependency aggregator that includes Logback as the primary logging implementation along with bridges for Log4j and Java Util Logging compatibility, ensuring unified logging through the SLF4J facade.

Package Information

  • Package Name: org.springframework.boot:spring-boot-starter-logging
  • Package Type: maven
  • Language: Java
  • Installation: Add to your pom.xml:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-logging</artifactId>
    <version>3.5.3</version>
</dependency>

Or in build.gradle:

implementation 'org.springframework.boot:spring-boot-starter-logging:3.5.3'

Core Imports

import org.springframework.boot.logging.LoggingSystem;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggerConfiguration;
import org.springframework.boot.logging.LoggerGroups;
import org.springframework.boot.logging.LoggerGroup;
import org.springframework.boot.logging.DeferredLog;
import org.springframework.boot.logging.DeferredLogs;
import org.springframework.boot.logging.CorrelationIdFormatter;
import org.springframework.boot.logging.logback.LogbackLoggingSystem;
import org.springframework.boot.logging.structured.StructuredLogFormatter;
import org.springframework.boot.logging.structured.CommonStructuredLogFormat;

Basic Usage

import org.springframework.boot.logging.LoggingSystem;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggerGroups;
import org.springframework.boot.logging.DeferredLog;

// Get the current logging system
LoggingSystem loggingSystem = LoggingSystem.get(getClass().getClassLoader());

// Set log level for a specific logger
loggingSystem.setLogLevel("com.example.MyClass", LogLevel.DEBUG);

// Get logger configurations
List<LoggerConfiguration> configurations = loggingSystem.getLoggerConfigurations();

// Use logger groups for bulk configuration
LoggerGroups loggerGroups = new LoggerGroups();
loggerGroups.putAll(Map.of("web", List.of("org.springframework.web", "org.springframework.http")));

// Use deferred logging during startup
DeferredLog log = new DeferredLog();
log.info("Early startup message");
log.switchTo(MyComponent.class); // Switch to real logger later

Architecture

Spring Boot Starter Logging is built around several key components:

  • Dependency Aggregation: Bundles Logback Classic, Log4j-to-SLF4J bridge, and JUL-to-SLF4J bridge
  • Logging System Abstraction: LoggingSystem provides a common interface over different logging implementations
  • Auto-Configuration: Spring Boot automatically detects and configures the logging system on startup
  • Default Configuration: Provides sensible defaults through XML configuration files in the classpath
  • Conversion Rules: Custom Logback conversion rules for formatting log output

Capabilities

Logging System Management

Core abstraction for managing logging systems programmatically.

/**
 * Common abstraction over logging systems
 */
public abstract class LoggingSystem {
    /**
     * Detect and return the logging system in use
     * @param classLoader class loader to use for detection
     * @return the detected LoggingSystem
     */
    public static LoggingSystem get(ClassLoader classLoader);
    
    /**
     * Reset logging system to limit output before full initialization
     */
    public void beforeInitialize();
    
    /**
     * Fully initialize the logging system
     * @param initializationContext the initialization context
     * @param configLocation location of configuration file (may be null)
     * @param logFile log file configuration
     */
    public void initialize(LoggingInitializationContext initializationContext, 
                          String configLocation, LogFile logFile);
    
    /**
     * Set the logging level for a specific logger
     * @param loggerName name of the logger
     * @param level the level to set
     */
    public void setLogLevel(String loggerName, LogLevel level);
    
    /**
     * Get current logger configurations
     * @return list of logger configurations
     */
    public List<LoggerConfiguration> getLoggerConfigurations();
    
    /**
     * Get configuration for a specific logger
     * @param loggerName name of the logger
     * @return logger configuration or null if not found
     */
    public LoggerConfiguration getLoggerConfiguration(String loggerName);
    
    /**
     * Get supported log levels for this logging system
     * @return set of supported log levels
     */
    public Set<LogLevel> getSupportedLogLevels();
    
    /**
     * Get logging system properties
     * @param environment the environment
     * @return logging system properties
     */
    public LoggingSystemProperties getSystemProperties(ConfigurableEnvironment environment);
    
    /**
     * Clean up the logging system
     */
    public void cleanUp();
    
    /**
     * Get a runnable for shutdown handling
     * @return shutdown handler runnable
     */
    public Runnable getShutdownHandler();
}

Logback Logging System

Logback-specific implementation of the logging system.

/**
 * LoggingSystem implementation for Logback
 */
public class LogbackLoggingSystem extends AbstractLoggingSystem {
    // Inherits all methods from LoggingSystem with Logback-specific implementations
}

Log Level Management

Enumeration of supported logging levels.

/**
 * Logging levels supported by a LoggingSystem
 */
public enum LogLevel {
    TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF;
    
    /**
     * Log message at this level
     * @param logger the logger to use
     * @param message the message to log
     */
    public void log(Log logger, Object message);
    
    /**
     * Log message with cause at this level
     * @param logger the logger to use
     * @param message the message to log
     * @param cause the throwable cause
     */
    public void log(Log logger, Object message, Throwable cause);
}

Logger Groups

Manage multiple loggers as a group for efficient level configuration.

/**
 * A collection of loggers that can be configured together
 */
public class LoggerGroups implements Iterable<LoggerGroup> {
    /**
     * Create an empty LoggerGroups
     */
    public LoggerGroups();
    
    /**
     * Create LoggerGroups with initial groups
     * @param namesAndMembers map of group names to member logger names
     */
    public LoggerGroups(Map<String, List<String>> namesAndMembers);
    
    /**
     * Add all groups from a map
     * @param namesAndMembers map of group names to member logger names
     */
    public void putAll(Map<String, List<String>> namesAndMembers);
    
    /**
     * Get a logger group by name
     * @param name the group name
     * @return the logger group or null if not found
     */
    public LoggerGroup get(String name);
    
    /**
     * Iterate over all logger groups
     * @return iterator for logger groups
     */
    public Iterator<LoggerGroup> iterator();
}

/**
 * A group of loggers that can be configured together
 */
public class LoggerGroup {
    /**
     * Get the group name
     * @return group name
     */
    public String getName();
    
    /**
     * Get the member logger names
     * @return list of logger names in this group
     */
    public List<String> getMembers();
    
    /**
     * Check if this group has any members
     * @return true if the group has members
     */
    public boolean hasMembers();
    
    /**
     * Get the configured log level for this group
     * @return configured log level or null if not set
     */
    public LogLevel getConfiguredLevel();
    
    /**
     * Configure log level for all members of this group
     * @param level the level to set
     * @param configurer function to configure each member logger
     */
    public void configureLogLevel(LogLevel level, BiConsumer<String, LogLevel> configurer);
}

Deferred Logging

Support for logging before the logging system is fully initialized.

/**
 * A Log implementation that can hold log events until initialization
 */
public class DeferredLog implements Log {
    /**
     * Create a new deferred log
     */
    public DeferredLog();
    
    // All standard Log interface methods
    public boolean isTraceEnabled();
    public boolean isDebugEnabled();
    public boolean isInfoEnabled();
    public boolean isWarnEnabled();
    public boolean isErrorEnabled();
    public boolean isFatalEnabled();
    
    public void trace(Object message);
    public void trace(Object message, Throwable t);
    public void debug(Object message);
    public void debug(Object message, Throwable t);
    public void info(Object message);
    public void info(Object message, Throwable t);
    public void warn(Object message);
    public void warn(Object message, Throwable t);
    public void error(Object message);
    public void error(Object message, Throwable t);
    public void fatal(Object message);
    public void fatal(Object message, Throwable t);
    
    /**
     * Switch deferred log to use a specific destination logger
     * @param destination the destination logger class
     */
    public void switchTo(Class<?> destination);
}

/**
 * Factory for creating deferred logs
 */
public interface DeferredLogFactory {
    /**
     * Get a deferred log for a class destination
     * @param destination the destination class
     * @return deferred log instance
     */
    Log getLog(Class<?> destination);
    
    /**
     * Get a deferred log for a log destination
     * @param destination the destination log
     * @return deferred log instance
     */
    Log getLog(Log destination);
    
    /**
     * Get a deferred log for a supplier destination
     * @param destination the destination supplier
     * @return deferred log instance
     */
    Log getLog(Supplier<Log> destination);
}

/**
 * Collection of deferred logs that can be switched over together
 */
public class DeferredLogs {
    /**
     * Get a deferred log for a specific destination
     * @param destination the destination class
     * @return deferred log instance
     */
    public DeferredLog getLog(Class<?> destination);
    
    /**
     * Switch all deferred logs to their final destinations
     */
    public void switchOverAll();
}

Correlation ID Support

Support for correlation IDs in log formatting for request tracing.

/**
 * Formatter for correlation IDs following W3C trace context specification
 */
public class CorrelationIdFormatter {
    /**
     * Default correlation ID formatter instance
     */
    public static final CorrelationIdFormatter DEFAULT;
    
    /**
     * Format correlation ID using the provided resolver
     * @param resolver function to resolve correlation values
     * @return formatted correlation ID string
     */
    public String format(UnaryOperator<String> resolver);
    
    /**
     * Format correlation ID to an appendable
     * @param resolver function to resolve correlation values
     * @param appendable target to append to
     * @throws IOException if appending fails
     */
    public void formatTo(UnaryOperator<String> resolver, Appendable appendable) throws IOException;
    
    /**
     * Create formatter from specification string
     * @param spec the correlation specification
     * @return correlation ID formatter
     */
    public static CorrelationIdFormatter of(String spec);
    
    /**
     * Create formatter from specification array
     * @param spec the correlation specification array
     * @return correlation ID formatter
     */
    public static CorrelationIdFormatter of(String[] spec);
    
    /**
     * Create formatter from specification collection
     * @param spec the correlation specification collection
     * @return correlation ID formatter
     */
    public static CorrelationIdFormatter of(Collection<String> spec);
}

Structured Logging Support

Support for structured log formats like Elastic Common Schema, Graylog, and Logstash.

/**
 * Interface for formatting log events into structured formats
 * @param <E> the log event type
 */
public interface StructuredLogFormatter<E> {
    /**
     * Format a log event as a string
     * @param event the log event
     * @return formatted string
     */
    String format(E event);
    
    /**
     * Format a log event as bytes
     * @param event the log event
     * @param charset the character set to use
     * @return formatted bytes
     */
    byte[] formatAsBytes(E event, Charset charset);
}

/**
 * Common structured log formats supported by Spring Boot
 */
public enum CommonStructuredLogFormat {
    /**
     * Elastic Common Schema format
     */
    ELASTIC_COMMON_SCHEMA,
    
    /**
     * Graylog Extended Log Format
     */
    GRAYLOG_EXTENDED_LOG_FORMAT,
    
    /**
     * Logstash JSON format
     */
    LOGSTASH
}

/**
 * Factory for creating structured log formatters
 */
public class StructuredLogFormatterFactory {
    // Factory methods for creating structured formatters
    // Implementation varies by logging system
}

/**
 * Manages context key-value pairs for structured logging
 */
public class ContextPairs {
    // Methods for managing structured logging context
    // Implementation provides key-value pair management
}

Stack Trace Printing

Customizable stack trace formatting for log output.

/**
 * Interface for formatting stack traces
 */
public interface StackTracePrinter {
    /**
     * Print stack trace to a string
     * @param throwable the throwable to print
     * @return stack trace as string
     */
    String printStackTraceToString(Throwable throwable);
    
    /**
     * Print stack trace to an appendable
     * @param throwable the throwable to print
     * @param out the target appendable
     * @throws IOException if writing fails
     */
    void printStackTrace(Throwable throwable, Appendable out) throws IOException;
}

/**
 * Standard implementation of stack trace printer
 */
public class StandardStackTracePrinter implements StackTracePrinter {
    /**
     * Create a standard stack trace printer
     */
    public StandardStackTracePrinter();
    
    // Implements StackTracePrinter methods with standard formatting
}

Logger Configuration

Immutable representation of logger configuration.

/**
 * Immutable class representing logger configuration
 */
public final class LoggerConfiguration {
    /**
     * Get the logger name
     * @return logger name
     */
    public String getName();
    
    /**
     * Get the configured level (may be null if inherited)
     * @return configured level
     */
    public LogLevel getConfiguredLevel();
    
    /**
     * Get the effective level (resolved through inheritance)
     * @return effective level
     */
    public LogLevel getEffectiveLevel();
    
    /**
     * Get level configuration considering inheritance
     * @return level configuration
     */
    public LevelConfiguration getLevelConfiguration();
    
    /**
     * Get level configuration for specific scope
     * @param scope the configuration scope
     * @return level configuration for the scope
     */
    public LevelConfiguration getLevelConfiguration(ConfigurationScope scope);
}

Log File Configuration

Configuration for log file settings.

/**
 * Represents a log file configuration
 */
public class LogFile {
    // File-based logging configuration methods
}

Logging Initialization Context

Context used during logging system initialization.

/**
 * Context used during logging system initialization
 */
public class LoggingInitializationContext {
    // Initialization context methods
}

Logging System Properties

Properties that should be applied to the logging system.

/**
 * Properties that should be applied to the logging system
 */
public class LoggingSystemProperties {
    // System properties methods
}

/**
 * Logback-specific system properties
 */
public class LogbackLoggingSystemProperties extends LoggingSystemProperties {
    // Logback-specific properties
}

Configuration Properties

System Properties

public static final String SYSTEM_PROPERTY = "org.springframework.boot.logging.LoggingSystem";
public static final String NONE = "none";
public static final String ROOT_LOGGER_NAME = "ROOT";
public static final String EXPECT_CORRELATION_ID_PROPERTY = "logging.expect-correlation-id";

Logging System Properties

The following system properties are available for logging configuration:

/**
 * System properties that can be configured for logging
 */
public enum LoggingSystemProperty {
    APPLICATION_NAME("logging.application-name"),
    APPLICATION_GROUP("logging.application-group"),  // New in Spring Boot 3.4+
    PID("logging.pid"),
    LOG_FILE("logging.file.name"),
    LOG_PATH("logging.file.path"),
    CONSOLE_CHARSET("logging.charset.console"),
    FILE_CHARSET("logging.charset.file"),
    CONSOLE_THRESHOLD("logging.threshold.console"),
    FILE_THRESHOLD("logging.threshold.file"),
    EXCEPTION_CONVERSION_WORD("logging.exception-conversion-word"),
    CONSOLE_PATTERN("logging.pattern.console"),
    FILE_PATTERN("logging.pattern.file"),
    CONSOLE_STRUCTURED_FORMAT("logging.structured.format.console"),  // New in Spring Boot 3.4+
    FILE_STRUCTURED_FORMAT("logging.structured.format.file"),        // New in Spring Boot 3.4+
    LEVEL_PATTERN("logging.pattern.level"),
    DATEFORMAT_PATTERN("logging.pattern.dateformat"),
    CORRELATION_PATTERN("logging.pattern.correlation");
    
    /**
     * Get the environment variable name for this property
     * @return environment variable name
     */
    public String getEnvironmentVariableName();
    
    /**
     * Get the application property name for this property
     * @return application property name
     */
    public String getApplicationPropertyName();
}

Logback Configuration Properties

The following properties can be configured in application.properties or application.yml:

  • logging.application-name - Application name for log formatting
  • logging.application-group - Application group for log formatting (Spring Boot 3.4+)
  • logging.charset.console - Console log charset (default: UTF-8)
  • logging.charset.file - File log charset (default: UTF-8)
  • logging.threshold.console - Console log threshold level
  • logging.threshold.file - File log threshold level
  • logging.pattern.console - Console log pattern format
  • logging.pattern.file - File log pattern format
  • logging.pattern.level - Log level pattern format
  • logging.pattern.dateformat - Date format pattern
  • logging.pattern.correlation - Correlation ID pattern format
  • logging.structured.format.console - Console structured format (Spring Boot 3.4+)
  • logging.structured.format.file - File structured format (Spring Boot 3.4+)
  • logging.exception-conversion-word - Exception conversion word

Custom Conversion Rules

Logback custom conversion rules provided by default configuration:

  • applicationName - Application name converter
  • clr - Color converter for console output
  • correlationId - Correlation ID converter for request tracing
  • esb - Enclosed in square brackets converter
  • wex - Whitespace throwable proxy converter
  • wEx - Extended whitespace throwable proxy converter

Default Configuration Files

The starter includes several default Logback configuration files:

  • defaults.xml - Default configuration with conversion rules and properties
  • base.xml - Base configuration including defaults, console and file appenders
  • console-appender.xml - Console appender configuration
  • file-appender.xml - File appender configuration
  • structured-console-appender.xml - Structured console appender
  • structured-file-appender.xml - Structured file appender

Dependencies Provided

This starter automatically includes the following dependencies:

  • ch.qos.logback:logback-classic - Main Logback logging implementation
  • org.apache.logging.log4j:log4j-to-slf4j - Bridge for Log4j 1.x to SLF4J
  • org.slf4j:jul-to-slf4j - Bridge for Java Util Logging to SLF4J

Standard Configuration File Lookup Order

Logback looks for configuration files in the following order:

  1. logback-test.groovy
  2. logback-test.xml
  3. logback.groovy
  4. logback.xml

If none are found, Spring Boot's default configuration is applied.

Factory Classes

Factory interfaces for creating and discovering logging systems.

/**
 * Factory interface for creating LoggingSystem instances
 */
public interface LoggingSystemFactory {
    /**
     * Get a logging system for the specified class loader
     * @param classLoader the class loader to use
     * @return the logging system
     */
    LoggingSystem getLoggingSystem(ClassLoader classLoader);
    
    /**
     * Create a factory from Spring Boot's spring.factories mechanism
     * @return logging system factory
     */
    static LoggingSystemFactory fromSpringFactories();
}

/**
 * Delegating factory that tries multiple logging system factories
 */
public class DelegatingLoggingSystemFactory implements LoggingSystemFactory {
    /**
     * Create a delegating factory with the given delegate factories
     * @param delegates the delegate factories
     */
    public DelegatingLoggingSystemFactory(List<LoggingSystemFactory> delegates);
    
    /**
     * Get a logging system using the delegate factories
     * @param classLoader the class loader
     * @return the logging system
     */
    public LoggingSystem getLoggingSystem(ClassLoader classLoader);
}

Usage Examples

Logger Groups Example

import org.springframework.boot.logging.LoggerGroups;
import org.springframework.boot.logging.LoggerGroup;
import org.springframework.boot.logging.LogLevel;

// Create logger groups for web and security components
Map<String, List<String>> groups = Map.of(
    "web", List.of("org.springframework.web", "org.springframework.http"),
    "security", List.of("org.springframework.security", "org.springframework.boot.autoconfigure.security")
);

LoggerGroups loggerGroups = new LoggerGroups(groups);

// Configure log level for entire web group
LoggerGroup webGroup = loggerGroups.get("web");
if (webGroup != null) {
    webGroup.configureLogLevel(LogLevel.DEBUG, (loggerName, level) -> {
        LoggingSystem.get(getClass().getClassLoader()).setLogLevel(loggerName, level);
    });
}

Deferred Logging Example

import org.springframework.boot.logging.DeferredLog;
import org.springframework.boot.logging.DeferredLogs;

// Create deferred logs for early startup logging
DeferredLogs deferredLogs = new DeferredLogs();
DeferredLog log = deferredLogs.getLog(MyStartupComponent.class);

// Log during early startup (before logging system is ready)
log.info("Starting up component...");
log.debug("Configuration loaded: {}", config);

// Later, switch all deferred logs to their final destinations
deferredLogs.switchOverAll();

Correlation ID Example

import org.springframework.boot.logging.CorrelationIdFormatter;

// Create custom correlation formatter
CorrelationIdFormatter formatter = CorrelationIdFormatter.of("traceId={traceId},spanId={spanId}");

// Use in log formatting
String correlationId = formatter.format(key -> {
    if ("traceId".equals(key)) return getCurrentTraceId();
    if ("spanId".equals(key)) return getCurrentSpanId();
    return null;
});

Structured Logging Example

import org.springframework.boot.logging.structured.CommonStructuredLogFormat;
import org.springframework.boot.logging.structured.StructuredLogFormatter;

// Configure for Elastic Common Schema
# application.properties
logging.structured.format.file=elastic-common-schema

// Or configure for Logstash format
logging.structured.format.console=logstash

Error Handling

The logging system may throw the following exceptions:

  • IllegalStateException - When logging system cannot be initialized
  • IllegalArgumentException - When invalid log level or logger name is provided
  • UnsupportedOperationException - Thrown by default implementations of setLogLevel(), getLoggerConfigurations(), and getLoggerConfiguration() when not implemented by specific logging system
  • IOException - When correlation ID formatting to appendable fails

Types

/**
 * Configuration scope for logger level configuration
 */
public enum ConfigurationScope {
    DIRECT, INHERITED
}

/**
 * Level configuration details
 */
public static class LevelConfiguration {
    /**
     * Create level configuration for a standard log level
     * @param level the log level
     * @return level configuration
     */
    public static LevelConfiguration of(LogLevel level);
    
    /**
     * Create level configuration for a custom level
     * @param levelName the custom level name
     * @return level configuration
     */
    public static LevelConfiguration ofCustom(String levelName);
    
    /**
     * Check if this is a custom level configuration
     * @return true if custom level
     */
    public boolean isCustom();
    
    /**
     * Get the name of the level
     * @return level name
     */
    public String getName();
}

Install with Tessl CLI

npx tessl i tessl/maven-org-springframework-boot--spring-boot-starter-logging
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
mavenpkg:maven/org.springframework.boot/spring-boot-starter-logging@3.5.x