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:
-
Logback tries to find a file called logback-test.xml in the classpath.
-
If no such file is found, logback tries to find a file called logback.groovy in the classpath.
If no such file is found, it checks for the file logback.xml in the classpath..
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.Configuratorinterface 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 desiredConfiguratorimplementation.If none of the above succeeds, logback configures itself automatically using the
BasicConfiguratorwhich 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.youkuaiyun.com/sadfishsc/article/details/47160213
本文详细介绍了如何自定义logback和log4j的日志文件路径,并解释了这两种日志框架的自动加载机制。针对logback,文章探讨了其在不同情况下的查找流程及如何使用特定依赖进行配置;对于log4j,则展示了如何通过配置属性来指定文件位置。
1259

被折叠的 条评论
为什么被折叠?



