如何使用外部属性文件在Springboot中使用log4j2?

时间:2018-12-17 06:42:08

标签: java spring-boot

我不想在春季引导中使用Exception in thread "main" java.lang.AbstractMethodError: org.apache.logging.log4j.core.config.ConfigurationFactory.getConfiguration(Lorg/apache/logging/log4j/core/config/ConfigurationSource;)Lorg/apache/logging/log4j/core/config/Configuration; at org.apache.logging.log4j.core.config.ConfigurationFactory$Factory.getConfiguration(ConfigurationFactory.java:510) at org.apache.logging.log4j.core.config.ConfigurationFactory$Factory.getConfiguration(ConfigurationFactory.java:450) at org.apache.logging.log4j.core.config.ConfigurationFactory.getConfiguration(ConfigurationFactory.java:257) at org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:560) at org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:577) at org.apache.logging.log4j.core.LoggerContext.start(LoggerContext.java:212) at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:152) at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:45) at org.apache.logging.log4j.LogManager.getContext(LogManager.java:194) at org.apache.logging.log4j.LogManager.getLogger(LogManager.java:551) at org.apache.logging.log4j.LogManager.getLogger(LogManager.java:537) at com.flight.testcode.App.<clinit>(App.java:11) 文件。我想使用外部属性文件,但显示错误。

<dependencies>
<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
   <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.6.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.6.1</version>
    </dependency>

Pom文件依赖性

{{1}}

那么我该如何使用外部属性文件。

  

它还不支持log4j2版本2.11.1吗?

3 个答案:

答案 0 :(得分:4)

添加以下依赖项

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>

然后在启动时指定日志记录配置:

-Dlogging.config=/path/to/log4j2.yaml (or .json or .xml)

答案 1 :(得分:1)

最后我找到了解决log42外部文件加载的方法。

import org.apache.logging.log4j.core.config.Configurator;

static {
   Configurator.initialize(null, "<filename>.properties");
}

如果我们不使用Configurator.initialize()方法,那么log4j2使用其默认配置。

答案 2 :(得分:0)

Log4j 将检查“log4j.configurationFile”系统属性,如果设置,将尝试加载配置。

如果您正在使用 gradle,并尝试运行测试方法,则必须将以下内容添加到 build.gradle。这使测试方法可以选择 -Dlog4j.configurationFile= 在测试运行期间选择:

测试{ systemProperty "log4j.configurationFile", System.getProperty("log4j.configurationFile") }

文件搜索的层次结构在文档 here 中解释: