網頁

2019/9/1

Spring Boot Log4j2 Maven Gradle dependencies 設定

Spring Boot的spring-boot-starter-logging預設是依賴logback,若同時又加入了log4j的依賴,就會導致classpath下有logback與log4j兩個日誌框架,並造成Spring Boot SLF4J: Class path contains multiple SLF4J bindings.的警告。

因此在Spring Boot專案若要使用log4j,必須在Maven的pom.xml或Gradle的build.gradle配置檔中把spring-boot-starter-logging的依賴給排除,然後改用spring-boot-starter-log4j2

在Spring Boot專案引入log4j2依賴Maven及Gradle配置範例如下。

Maven - pom.xml

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</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-web</artifactId>
<!-- Maven專案中若有spring-boot-starter依賴且已排除了spring-boot-starter-logging,下面就不用設定了
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
-->
    </dependency>
    <!-- log4j2 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>
    ...
</dependencies>

Gradle - build.gradle

dependencies {
    implementation ('org.springframework.boot:spring-boot-starter') {
        exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
    }
    implementation ('org.springframework.boot:spring-boot-starter-web') {
        exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
    }
    implementation 'org.springframework.boot:spring-boot-starter-log4j2'
    // other implementations...
}

或是Gradle可設定全域排除。

Gradle - build.gradle

configurations.all {
    exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-log4j2'
    // other implementations...
}

Spring Boot預設的日誌輸出等級INFO。但若Sprinb Boot改用了log4j2框架並添加了設定檔如log4j2.properties,即使在沒作任何設定的情況下,Logger預設等級會改為log4j2的預設等級ERROR

src/main/resources下新增log4j2.properties並設定以下在console輸出日誌。

log4j2.properites

appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
 
rootLogger.level = INFO
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT


參考:

沒有留言:

張貼留言