知識庫 / Spring / Spring Boot RSS 訂閱

Spring Boot Logback 和 Log4j2 擴展

Logging,Spring Boot
HongKong
10
11:46 AM · Dec 06 ,2025

1. 概述

日誌記錄是任何軟件應用程序的重要組成部分,它有助於故障排除和調試問題。此外,還可以用於監控目的。Spring Boot 支持流行的日誌框架,例如 Logback 和 Log4j2。 Spring Boot 提供了一些擴展用於 Logback 和 Log4j2,這些擴展可能對高級配置有所幫助

在本教程中,我們將研究 Spring Boot 應用程序中的 Logback 和 Log4j2 擴展。

2. Logback 擴展

Spring Boot 默認使用 Logback 庫進行日誌記錄。 在本部分,我們將學習一些 Logback 的擴展,這些擴展可以幫助您進行高級配置。

值得注意的是,Spring Boot 建議使用 logback-spring.xml 代替默認的 logback.xml由於 logback.xml 配置文件的加載過早,因此我們不能在標準 logback.xml 中使用擴展。

2.1. Maven 依賴

要使用 Logback,我們需要將 <em >logback-classic</em> 依賴添加到我們的 <em >pom.xml</em> 中。但是,<em >logback-classic</em> 依賴已經在 Spring Boot Starter 依賴中可用。

因此,我們只需要將 <a href="https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web">spring-boot-starter-web依賴添加到pom.xml` 中:

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

2.2. 基本日誌記錄

首先,我們將添加一些日誌記錄到主 Spring Boot 類,以便在我們的示例中使用:

@SpringBootApplication
public class SpringBootLogbackExtensionsApplication {

    private static final Logger logger = LoggerFactory.getLogger(SpringBootLogbackExtensionsApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(SpringBootLogbackExtensionsApplication.class, args);

        logger.debug("Debug log message");
        logger.info("Info log message");
        logger.error("Error log message");
        logger.warn("Warn log message");
        logger.trace("Trace log message");
    }
}

2.3. 針對特定配置的設置

Spring 配置(profile)提供了一種調整應用程序配置的方法,基於當前激活的配置(profile)。

例如,我們可以為不同的環境(如 “development”“production”)定義不同的 Logback 配置。 如果我們希望使用單一的 Logback 配置,可以使用 springProfile 元素在 logback-spring.xml 中。

通過使用 springProfile 元素,可以根據激活的 Spring 配置(profile)可選地包含或排除配置部分。可以使用 name 屬性來指定哪個配置(profile)接受該配置。

默認情況下,Spring Boot 只將日誌輸出到控制枱。現在,假設我們希望將日誌輸出到文件,併為 “production” 使用文件,為 “development” 使用控制枱。 我們可以通過使用 springProfile 元素輕鬆實現。

讓我們創建一個 logback-spring.xml 文件:

<springProfile name="development">
    <appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern>
        </layout>
    </appender>
    <root level="info">
        <appender-ref ref="Console" />
    </root>
</springProfile>

<springProfile name="production">
    <appender name="RollingFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOGS}/spring-boot-logger.log</file>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <Pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOGS}/archived/spring-boot-logger-%d{yyyy-MM-dd}.log</fileNamePattern>
        </rollingPolicy>
    </appender>
    <root level="info">
        <appender-ref ref="RollingFile" />
    </root>
</springProfile>

然後,我們可以使用 JVM 系統參數 -Dspring.profiles.active=development-Dspring.profiles.active=production 設置活動配置文件。

現在,如果我們使用 development 配置文件運行 Spring Boot 應用程序,我們將在控制枱中獲得以下輸出:

10:31:13.766 [main] INFO  c.b.e.SpringBootLogbackExtensionsApplication - Info log message
10:31:13.766 [main] ERROR c.b.e.SpringBootLogbackExtensionsApplication - Error log message
10:31:13.766 [main] WARN  c.b.e.SpringBootLogbackExtensionsApplication - Warn log message

此外,我們可能需要將信息記錄到文件上,用於“測試環境”或“生產環境”。為了支持此功能,springProfile’s name 屬性接受一個 profile 表達式。Profile 表達式允許更復雜的 profile 邏輯:

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

上述配置在以下情況啓用:當 “production”“staging” 配置文件處於活動狀態時。

2.4. 環境屬性

有時,我們需要從 application.properties 文件中訪問日誌配置中的值。 在這種情況下,我們使用 Logback 配置中的 springProperty 元素。

springProperty 元素類似於 Logback 的標準 property 元素。 但是,我們可以通過環境確定屬性的來源,而不是指定直接的值。

springProperty 元素具有 source 屬性,它取值為應用程序屬性的值。 如果環境未設置屬性,則它將從 defaultValue 屬性中獲取默認值。 此外,我們需要將值設置為 name 屬性,以便在配置中的其他元素中引用該屬性。

最後,我們可以設置 scope 屬性。 在 context 作用域中的屬性是上下文的一部分,並且在所有日誌事件中可用。

假設我們想將應用程序名稱用作日誌文件的名稱。 首先,我們在 application.properties 文件中定義應用程序名稱:

spring.application.name=logback-extension

然後,我們將應用程序名稱暴露用於在 logback-spring.xml 中使用:

<property name="LOGS" value="./logs" />
<springProperty scope="context" name="application.name" source="spring.application.name" />
<springProfile name="production">
    <appender name="RollingFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOGS}/${application.name}.log</file>
        <!-- configuration -->
    </appender>
</springProfile>

在上述配置中,我們設置了 source 屬性,將 springProperty 元素指向 spring.application.name 屬性。此外,我們使用 ${application.name} 引用該屬性。

在下一部分,我們將討論 Spring Boot 應用程序中的 Log4j2 擴展。

3. Log4j2 擴展

Log4j2 擴展與 Logback 擴展類似。在標準 log4j2.xml 配置文件中不能使用擴展,因為該文件在加載過早

建議在 Spring Boot 中,將 Log4j2 配置存儲在名為 log4j2-spring.xml 的單獨文件中。Spring Boot 在存在該文件的情況下,會在任何其他 Log4j2 配置之前加載它。

3.1. Maven 依賴

為了使用 Log4j2 庫而不是默認的 Logback,我們需要 從我們的 starter 依賴中排除 Logback

<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>

此外,我們需要將 spring-boot-starter-log4j2log4j-spring-boot 依賴項添加到我們的 pom.xml 文件中:

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

我們包含 log4j-spring-boot 庫,以便在 Log4j2 設置中使用 Spring Boot 配置文件。如果沒有此依賴項,我們將看到以下錯誤消息:

2023-01-21 15:56:12,473 main ERROR Error processing element SpringProfile ([Loggers: null]): CLASS_NOT_FOUND

3.2. 針對特定配置的設置

雖然將設置放入不同的日誌配置中在大多數情況下都有效,但在某些情況下,我們可能希望為不同的環境使用單一的日誌設置。在這種情況下,我們可以使用 SpringProfile 元素,通過向配置中添加 Spring Boot 配置文件來完成

讓我們編寫一個簡單的 log4j2-spring.xml

<SpringProfile name="development">
    <Logger name="com.baeldung.extensions" level="debug"></Logger>
</SpringProfile>

<SpringProfile name="production">
    <Logger name="com.baeldung.extensions" level="error"></Logger>
</SpringProfile>

這與我們在 Logback 部分討論的示例類似。

如果我們在生產環境(production)下運行應用程序,我們現在將看到應用程序的 ERROR 日誌,並且不再有 com.baeldung.extensions 包的 DEBUG 日誌。

2023-01-22T11:19:52,885 ERROR [main] c.b.e.SpringBootLog4j2ExtensionsApplication: Error log message
2023-01-22T11:19:52,885 FATAL [main] c.b.e.SpringBootLog4j2ExtensionsApplication: Fatal log message

需要注意的是,SpringProfile 節可以在 configuration 元素內的任何位置使用。

3.3. 環境屬性查找

Log4j2 Lookups 提供了一種方式,用於為我們的日誌配置文件的值提供。

我們可以使用 Log4j2 Lookup 從 application.properties 文件中訪問值。 此外,我們還可以使用活動和默認 profile 的值。 要做到這一點,在我們的 Log4j2 配置中,我們可以使用 spring- 前綴的 Lookup。

讓我們在 application.properties 文件中設置 spring.application.name=log4j2-extension。 然後,我們從 Spring 環境中讀取 spring.application.name

<Console name="Console-Extensions" target="SYSTEM_OUT">
    <PatternLayout
        pattern="%d %p %c{1.} [%t] ${spring:spring.application.name} %m%n" />
</Console>

在上述配置中,我們使用 spring.application.name 屬性,並利用 spring 預置查找。運行後,應用程序會將以下消息記錄到控制枱:

2023-01-22 16:17:30,301 ERROR c.b.e.SpringBootLog4j2ExtensionsApplication [main] log4j2-extension Error log message
2023-01-22 16:17:30,301 FATAL c.b.e.SpringBootLog4j2ExtensionsApplication [main] log4j2-extension Fatal log message

3.4. Log4j2 系統屬性

Log4j2 提供了一系列 系統屬性,可用於配置各種方面。我們可以將這些系統屬性添加到 log4j2.system.properties 文件中。

讓我們添加 log4j2.debug=true 屬性。此係統屬性會將所有內部日誌輸出到控制枱:

TRACE StatusLogger Log4jLoggerFactory.getContext() found anchor class java.util.logging.Logger

此外,我們還可以向 application.properties文件中添加系統屬性。 log4j2.system.properties文件中定義的屬性優先級高於 application.properties文件。

4. 結論

Spring Boot 提供了廣泛的日誌支持。在本教程中,我們探討了 Spring Boot 中 Logback 和 Log4j2 擴展。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.