1. 程式人生 > >Spring Boot與Log4j2整合之java.lang.IllegalStateException: Logback configuration error detected:

Spring Boot與Log4j2整合之java.lang.IllegalStateException: Logback configuration error detected:

引言: 一個問題的分析與解決過程是表與裡的過程,是一個大膽猜測與小心求證的過程,spring boot與log4j2的整合過程中,我將描述一下分析這個問題的思路和過程。 我一直強調一點: 重要的不是解決問題的結論,而是解決問題的思路和方法,即使在解決完問題之後,依然需要回過頭覆盤,在問題分析過程中的走過的彎路。

1 專案情況介紹

Spring Boot 1.5.7 , JDK 1.8, Log4j2.7
在這個專案中,希望整合Log4j2作為預設的日誌系統輸出器。
Log4j2.xml的定義如下:

"><Configuration status="off">
    <Properties
>
<Property name="LOG_PATH">.</Property> </Properties> <Appenders> <!-- Console --> <Console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %logger{36}.%[email protected]%L - %msg%n"
/>
<!--<PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %C{5} (%F:%L) - %msg%n"/>--> </Console> <!-- RollingFile --> <RollingRandomAccessFile name="RollingFile" fileName="./aifasion.log" filePattern
="${LOG_PATH}/aifasion.log.%d{yyyy-MM-dd-HH}">
<PatternLayout pattern="%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger{36}.%[email protected]%L - %msg%n"/> <Policies> <TimeBasedTriggeringPolicy/> </Policies> <DefaultRolloverStrategy max="30"/> </RollingRandomAccessFile> </Appenders> <Loggers> <!-- Spring Loggers --> <Logger name="org.springframework" level="info"/> <!-- App Loggers --> <Logger name="org.jd.test" level="debug" additivity="false"> <AppenderRef ref="Console"/> <AppenderRef ref="RollingFile"/> </Logger> <!-- Root Logger --> <Root level="info"> <AppenderRef ref="Console"/> <AppenderRef ref="RollingFile"/> </Root > </Loggers> </Configuration>

application.properties的檔案定義如下:

server.port=8080
logging.config=classpath:log4j2.xml
debug=true

上述為核心的配置檔案資訊。
在pom.xml中,針對spring-boot-web中對於logging的引用進行了排除,配置資訊如下:

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

2 問題描述

基於Spring Boot的嚮導建立基礎專案,整合Log4j2,在專案啟動過程中,報出如下的錯誤資訊:

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/D:/DevSpace/M2Space/ch/qos/logback/logback-classic/1.1.11/logback-classic-1.1.11.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/D:/DevSpace/M2Space/org/apache/logging/log4j/log4j-slf4j-impl/2.7/log4j-slf4j-impl-2.7.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]
The Class-Path manifest attribute in D:\DevSpace\M2Space\org\apache\derby\derby\10.13.1.1\derby-10.13.1.1.jar referenced one or more files that do not exist: D:\DevSpace\M2Space\org\apache\derby\derby\10.13.1.1\derbyLocale_cs.jar,D:\DevSpace\M2Space\org\apache\derby\derby\10.13.1.1\derbyLocale_de_DE.jar,D:\DevSpace\M2Space\org\apache\derby\derby\10.13.1.1\derbyLocale_es.jar,D:\DevSpace\M2Space\org\apache\derby\derby\10.13.1.1\derbyLocale_fr.jar,D:\DevSpace\M2Space\org\apache\derby\derby\10.13.1.1\derbyLocale_hu.jar,D:\DevSpace\M2Space\org\apache\derby\derby\10.13.1.1\derbyLocale_it.jar,D:\DevSpace\M2Space\org\apache\derby\derby\10.13.1.1\derbyLocale_ja_JP.jar,D:\DevSpace\M2Space\org\apache\derby\derby\10.13.1.1\derbyLocale_ko_KR.jar,D:\DevSpace\M2Space\org\apache\derby\derby\10.13.1.1\derbyLocale_pl.jar,D:\DevSpace\M2Space\org\apache\derby\derby\10.13.1.1\derbyLocale_pt_BR.jar,D:\DevSpace\M2Space\org\apache\derby\derby\10.13.1.1\derbyLocale_ru.jar,D:\DevSpace\M2Space\org\apache\derby\derby\10.13.1.1\derbyLocale_zh_CN.jar,D:\DevSpace\M2Space\org\apache\derby\derby\10.13.1.1\derbyLocale_zh_TW.jar
10:00:46.441 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : []
10:00:46.444 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Excluded patterns for restart : [/spring-boot-starter/target/classes/, /spring-boot-autoconfigure/target/classes/, /spring-boot-starter-[\w-]+/, /spring-boot/target/classes/, /spring-boot-actuator/target/classes/, /spring-boot-devtools/target/classes/]
10:00:46.444 [main] DEBUG org.springframework.boot.devtools.restart.ChangeableUrls - Matching URLs for reloading : [file:/D:/workspace/testdemo/target/classes/]
Logging system failed to initialize using configuration from ‘classpath:log4j2.xml’
java.lang.IllegalStateException: Logback configuration error detected:
ERROR in [email protected]:17 - no applicable action for [Properties], current ElementPath is [[Configuration][Properties]]
ERROR in [email protected]:35 - no applicable action for [Property], current ElementPath is [[Configuration][Properties][Property]]
ERROR in [email protected]:16 - no applicable action for [Appenders], current ElementPath is [[Configuration][Appenders]]
ERROR in [email protected]:53 - no applicable action for [Console], current ElementPath is [[Configuration][Appenders][Console]]
ERROR in [email protected]:92 - no applicable action for [PatternLayout], current ElementPath is [[Configuration][Appenders][Console][PatternLayout]]
ERROR in [email protected]:91 - no applicable action for [RollingRandomAccessFile], current ElementPath is [[Configuration][Appenders][RollingRandomAccessFile]]
ERROR in [email protected]:106 - no applicable action for [PatternLayout], current ElementPath is [[Configuration][Appenders][RollingRandomAccessFile][PatternLayout]]
ERROR in [email protected]:23 - no applicable action for [Policies], current ElementPath is [[Configuration][Appenders][RollingRandomAccessFile][Policies]]
ERROR in [email protected]:45 - no applicable action for [TimeBasedTriggeringPolicy], current ElementPath is [[Configuration][Appenders][RollingRandomAccessFile][Policies][TimeBasedTriggeringPolicy]]
ERROR in [email protected]:48 - no applicable action for [DefaultRolloverStrategy], current ElementPath is [[Configuration][Appenders][RollingRandomAccessFile][DefaultRolloverStrategy]]
ERROR in [email protected]:14 - no applicable action for [Loggers], current ElementPath is [[Configuration][Loggers]]
ERROR in [email protected]:59 - no applicable action for [Logger], current ElementPath is [[Configuration][Loggers][Logger]]
ERROR in [email protected]:69 - no applicable action for [Logger], current ElementPath is [[Configuration][Loggers][Logger]]
ERROR in [email protected]:42 - no applicable action for [AppenderRef], current ElementPath is [[Configuration][Loggers][Logger][AppenderRef]]
ERROR in [email protected]:46 - no applicable action for [AppenderRef], current ElementPath is [[Configuration][Loggers][Logger][AppenderRef]]
ERROR in [email protected]:29 - no applicable action for [Root], current ElementPath is [[Configuration][Loggers][Root]]
ERROR in [email protected]:41 - no applicable action for [AppenderRef], current ElementPath is [[Configuration][Loggers][Root][AppenderRef]]
ERROR in [email protected]:45 - no applicable action for [AppenderRef], current ElementPath is [[Configuration][Loggers][Root][AppenderRef]]
at org.springframework.boot.logging.logback.LogbackLoggingSystem.loadConfiguration(LogbackLoggingSystem.java:162)
at org.springframework.boot.logging.AbstractLoggingSystem.initializeWithSpecificConfig(AbstractLoggingSystem.java:66)
at org.springframework.boot.logging.AbstractLoggingSystem.initialize(AbstractLoggingSystem.java:56)
at org.springframework.boot.logging.logback.LogbackLoggingSystem.initialize(LogbackLoggingSystem.java:115)
at org.springframework.boot.logging.LoggingApplicationListener.initializeSystem(LoggingApplicationListener.java:308)
at org.springframework.boot.logging.LoggingApplicationListener.initialize(LoggingApplicationListener.java:276)
at org.springframework.boot.logging.LoggingApplicationListener.onApplicationEnvironmentPreparedEvent(LoggingApplicationListener.java:239)
at org.springframework.boot.logging.LoggingApplicationListener.onApplicationEvent(LoggingApplicationListener.java:212)
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172)
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:122)
at org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:74)
at org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:54)
at org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:325)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:296)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107)
at org.jd.test.TestdemoApplication.main(TestdemoApplication.java:14)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)

以上是在系統啟動過程中的錯誤資訊,關鍵錯誤資訊是:

Logging system failed to initialize using configuration from ‘classpath:log4j2.xml’
java.lang.IllegalStateException: Logback configuration error detected:

3 問題分析過程

3.1 配置檔案的格式或者定義錯誤

根據剛才看到的錯誤資訊,第一反應是log4j2.xml中定義的錯誤資訊或者格式資訊有誤。
根據這個判斷,就直接在Log4j2的官方文件上,重新查閱了一番,結合定義中的內容格式,感覺格式都是完全正確的,沒有什麼出入問題。
於是,我就使用排除法,將Log4j2.xml中的內容按照步驟,一部分一部分的進行驗證排除,如果哪個部分中存在配置檔案的配置錯誤,則可以定位出來。
在一番定位之後,發現只要配置檔案中存在內容,就會報出類似錯誤資訊。
結論是,應該不是配置檔案的配置錯誤資訊。

3.2 下載樣例專案進行分析

於是,從網上直接下來了spring-boot中自帶的spring-boot-sample-actuator-log4j2專案,進行分析:
發現其中pom.xml中的不同之處為:

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

而之前的exclusion是在spring-boot-web-starter中排除的,就是這各位置的不同造成的。
換個角度來分析,可以得出在spring-boot-web-starter中exclude掉的logging並未完全清楚乾淨,還有其他的類庫或者包存在類似的以來。

4. 問題的解決

將spring-boot-starter-logging的包在spring-boot-starter中直接排除掉,從spring boot整體上進行替換,就可以解決這個問題:

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

5 反思分析過程

在這個分析過程中,在看到日誌的錯誤之時,第一反應就是配置檔案的配置錯誤,這個方向從一開始就是錯誤的。
在Pom.xml中雖然進行了exclude操作,但是並未真正的徹底排除掉logging;在看到樣例程式之後,才感知到時logging的遺漏引用存在導致了問題。
我又重新檢視一遍專案中報出的異常日誌,發現了一個我疏忽的細節問題:

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/D:/DevSpace/M2Space/ch/qos/logback/logback-classic/1.1.11/logback-classic-1.1.11.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/D:/DevSpace/M2Space/org/apache/logging/log4j/log4j-slf4j-impl/2.7/log4j-slf4j-impl-2.7.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]

在這個提示資訊裡面,明確了告知logging有多個繫結,logback、log4j2兩種實現;目前使用的是logback的繫結,這個提示資訊竟然忽略了…….

其實這個提示資訊已經明確告知了問題出現的根源,只是當時被無意或者有意的忽略了…..

6 總結

經過這個問題的分析過程,我們可以得知,異常日誌或者錯誤日誌的分析是第一現場,非常的重要,它給了我們大量而豐富的第一手資訊,為我們分析和解決問題提示了非常多的方向,需要進行慎重和小心的求證與驗證。
之後是exclude logging的依賴,雖然進行exclude排除操作,卻並未完全進行替換掉,這個是在包的依賴中遺漏掉的。

相關推薦

Spring BootLog4j2整合java.lang.IllegalStateException: Logback configuration error detected:

引言: 一個問題的分析與解決過程是表與裡的過程,是一個大膽猜測與小心求證的過程,spring boot與log4j2的整合過程中,我將描述一下分析這個問題的思路和過程。 我一直強調一點: 重要的不是解決問題的結論,而是解決問題的思路和方法,即使在解決完問題之後,

Activiti學習spring boot activiti整合

1、新建spring boot 專案 使用IDEA新建一個spring boot 專案,專案結構如下: 2、增加activiti、jpa、mysql等依賴 <dependencies> <dependency&

spring boot 集成axis1.4 java.lang.NoClassDefFoundError: Could not initialize class org.apache.axis.client.AxisClient

could not cli PC com 定義 logging axis found 調用 pom配置: <dependencies> <dependency> <groupId>org.springframewor

resin發布spring-boot項目報錯“java.lang.NoSuchMethodError: org.jboss.logging.Logger.getMessageLogger”

圖片 ssa 項目啟動 chm dep bubuko ava initial 4.3 說白了還是jar包沖突問題,直接說解決方式: 首先將resin/lib下的validation-api-1.0.0.GA.jar替換成項目中的包validation-api-2.0.1.F

從零實現 Spring Boot 2.0 整合 weixin-java-mp(weixin-java-tools) 獲取 openId,用於微信授權

步驟: 一、內網穿透申請二級域名(有伺服器和域名者可略過) 二、申請微信公眾平臺測試號(有已認證的微信服務號者可略過) 三、搭建 Spring Boot 2.0 專案實現獲取openId 一、內網穿透: 因為要直接用內網本機開發除錯,微信網頁授權在回撥時要訪問本機,所以直接

6、Spring Boot MyBatis整合

1.6 Spring Boot 與MyBatis整合 簡介 詳細介紹如何在Spring Boot中整合MyBatis,並通過註解方式實現對映。 完整原始碼: 1.6.1 建立 spring-boot-mybatis 專案 pom檔案如下 <?xml version="1

7、Spring Boot Redis 整合

1.7 Spring Boot 與 Redis 整合 簡介 繼續上篇的MyBatis操作,詳細介紹在Spring Boot中使用RedisCacheManager作為快取管理器,整合業務於一體。 完整原始碼: Spring-Boot-Demos 1.7.1 建立 spring-boot-r

Spring BootReact整合

前言 前不久學習了Web開發,用React寫了前端,Spring Boot搭建了後端,然而沒有成功地把兩個工程結合起來,造成前端與後端之間需要跨域通訊,帶來了一些額外的工作。 這一次成功地將前端工程與後端結合在一個Project中,記錄一下,也希望能幫到那些和我一樣的入門小白。 環境 Win

Spring BootQuartz整合

1.匯入依賴包 <!-- quartz定時器 --> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artif

spring boot中使用jackson出現java.lang.NoClassDefFoundError: Could not initialize class com.fasterxml.jack

Jackson Dependency Issue in Spring Boot with Maven Build In this article, a Spring Boot 1.3.3 dependency issue is explored and an override is provid

spring bootlog4j2日誌級別控制順序

如果classpath下有log4j2.xml。則日誌級別由log4j2.xml控制。log4j2.xml中的<Configuration status="info" monitorInterv

spring bootjunit整合測試

  先建立一個REST介面 package com.laoxu.gamedog.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframew

Spring boot+ Mybatis 完美整合註解版

開發環境: 開發工具:Intellij IDEA 2017.1.3JDK : 1.8.0_101spring boot 版本 : 1.5.8.RELEASEmaven : 3.3.9 拓展: springboot 整合 Mybatis 事務管理 開始 1.新建一個spr

spring boot mybatis整合

本專案使用的環境: 開發工具:Intellij IDEA 2018.1.3 springboot: 2.0.5.RELEASE jdk:1.8.0_161 maven:3.5.3 首先先建立springboot專案 選擇需要的模組 填寫包名 1.開始在專案

spring boot Mybatis整合(*)

業務層 tomcat ng- quest map big selectall esp 連接 在pom.xml文件中加入數據庫、spring-mybatis整合 <!-- spring boot 整合mybatis --> <de

Spring Cloud RestTemplate報錯:java.lang.IllegalStateException: No instances available for

java.lang.IllegalStateException: No instances available for localhost     原:restTemplate.getForObject( uri+"/user/getname",User.clas

spring cloud feign:Caused by: java.lang.IllegalStateException: RequestParam.value() was empty on parameter 0

use except app caused ise als stp lstat name 報錯之前: @RequestMapping(value = "hi", method = RequestMethod.GET)String hiService(@Request

spring boot】【elasticsearch】spring boot整合elasticsearch,啟動報錯Caused by: java.lang.IllegalStateException: availableProcessors is already set to [8], reje

  spring boot整合elasticsearch, 啟動報錯: Caused by: java.lang.IllegalStateException: availableProcessors is already set to [8], rejecting [8] at

spring bootjdbcTemplate的整合案例2

database bean n) ret struct mapping rri ott mode 簡單入門了spring boot後,接下來寫寫跟數據庫打交道的案例。博文采用spring的jdbcTemplate工具類與數據庫打交道。 下面是搭建的springbo

SpringBoot旅 -- 定時任務兩種(Spring Schedule Quartz 整合 )實現

目的 config object cnblogs java title cor 進行 eat 相關文章 Spring Boot 相關文章目錄 前言 最近在項目中使用到定時任務,之前一直都是使用Quartz 來實現,最近看Spring 基礎發現其實Spring 提供