1. 程式人生 > >spring如何自定義載入logback.xml

spring如何自定義載入logback.xml

1、前言

做過專案的朋友們都知道,只要把logback或者log4j放在下,容器就可以自動載入日誌檔案。但是如何自定義日誌檔案的路徑呢?

2、logback的自動載入

從官方文件中找找原因:

Logback can be configured either programmatically or with a configuration script expressed in XML or Groovy format. By the way, existing log4j users can convert their log4j.properties files to logback.xml

using our PropertiesTranslator web-application.

Let us begin by discussing the initialization steps that logback follows to try to configure itself:

  1. Logback tries to find a file called logback-test.xml in the classpath.

  2. If no such file is found, logback tries to find a file called logback.groovy

    in the classpath.

  3. If no such file is found, it checks for the file logback.xml in the classpath..

  4. If no such file is found, service-provider loading facility (introduced in JDK 1.6) is used to resolve the implementation of com.qos.logback.classic.spi.Configurator interface by looking up the file META-INF\services\ch.qos.logback.classic.spi.Configurator

    in the class path. Its contents should specify the fully qualified class name of the desired Configurator implementation.

  5. If none of the above succeeds, logback configures itself automatically using the BasicConfigurator which will cause logging output to be directed to the console.

從官方文件中,我們得知:

        logback框架首先會在classpath 尋找一系列相關檔案,如下:


如果找不到就會 service-provider載入JDK1.6+中的配置。

從上圖中我們可以就知道了為什麼logback.xml放在classpath就可以載入了。

3、log4j路徑的自定義配置

從spring容器的的監聽器中,我們並沒有到關於logback的監聽器,如圖:


但是我們可以看到log4j的監聽器,我們不妨先看一下log4j的初始化過程,進入contextInitialized()方法,我們可以看到:


通過說明我們知道,通過log4jConfigLocation屬性我們指定log4j檔案的位置,和spring的核心監聽器配置相同。

但是配置的時候,需要注意的是:日誌監聽器必須配置在spring核心監聽器之前.

原因如圖:


logback要想實現自定義配置,則也要實現相應的方法.

4、logback路徑的自定義配置

其實logback官方提供了相應的依賴,只是我們習慣直接放在classpath下,所以就淡化了該依賴。

<dependency>  
    <groupId>org.logback-extensions</groupId>  
    <artifactId>logback-ext-spring</artifactId>  
    <version>0.1.2</version>  
</dependency> 

從原始碼中我們可以看到和log4j類似的實現,如圖:

再看看作者是不是log4j配置的作者?


web.xml 中的配置:

<context-param>  
      <param-name>logbackConfigLocation</param-name> 
      <!-- 這裡可以配置自定義的路徑 --> 
      <param-value>classpath:logback.xml</param-value>  
</context-param>  
<listener>  
      <listener-class>ch.qos.logback.ext.spring.web.LogbackConfigListener</listener-class>  
</listener>  

到這裡我們那就可以自己實現了。具體的細節可以參考下面的技術部落格。

需要注意的是:日誌的監聽器和spring的核心監聽器都是實現了

5、參考文件

官方文件:https://logback.qos.ch/manual/configuration.html

技術部落格:https://blog.csdn.net/sadfishsc/article/details/47160213