扩展 logback 配置

Extend logback configuration

有没有办法将多个logback配置文件组合在一起?假设有一个包含多个项目的父项目,我希望所有项目都使用相同的基本配置或基本 logback.xml 文件,但我想为每个项目添加或更改一些内容。这能做到吗?

不太了解,但听说可以借助属性为 log4j 完成类似的操作。

我认为您正在寻找文件包含功能。在一个以 <included> 元素为根的文件中创建通用基础功能,然后使用 <include> 元素从各种配置文件中包含它。

这在手册的 Configuration 章节中通过示例进行了描述:

Joran supports including parts of a configuration file from another file. This is done by declaring a <include> element, as shown below:

Example: File include (logback-examples/src/main/resources/chapters/configuration/containingConfig.xml)

<configuration>
  <include file="src/main/java/chapters/configuration/includedConfig.xml"/>

  <root level="DEBUG">
    <appender-ref ref="includedConsole" />
  </root>

</configuration>

The target file MUST have its elements nested inside an <included> element. For example, a ConsoleAppender could be declared as:

Example: File include (logback-examples/src/main/resources/chapters/configuration/includedConfig.xml)

<included>
  <appender name="includedConsole" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>"%d - %m%n"</pattern>
    </encoder>
  </appender>
</included>

Again, please note the mandatory <included> element.

The contents to include can be referenced as a file, as a resource, or as a URL.

  • As a file: To include a file use the file attribute. You can use relative paths but note that the current directory is defined by the application and is not necessarily related to the path of the configuration file.
  • As a resource: To include a resource, i.e a file found on the class path, use the resource attribute.
    <include resource="includedConfig.xml"/>
    
  • As a URL: To include the contents of a URL use the url attribute.
    <include url="http://some.host.com/includedConfig.xml"/>