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


  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值