2015-02-05 226 views
9

与文档状态完全一样,Log4j2与Spring Boot配合良好,通过根类路径中的log4j2.xml配置文件。如何在Java Spring Boot中更改log4j2.xml的默认位置?

虽然尝试将此文件移动到其他位置,但我无法在启动时将新位置传递给Spring。从the documentation

的各种记录系统可以通过包括在类路径的 相应的库被激活,并且进一步定制通过 提供在类路径的根中的位置所指定的合适的配置文件, 或by Spring环境物业 logging.config

我试图用Java系统属性

java -jar -Dlogging.config="classpath:/config/log4j2.xml" target/app.jar 

设置的新位置,或者使用外部application.properties包含相关财产

logging.config=classpath:/config/log4j2.xml 

但我经常通过以下错误消息映入眼帘。

ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console. 
+0

你能否确认'/ config'是否在类路径中?如果您使用的是基于Maven的项目,把XML文件下'的src/main/resources' – Mithun 2015-02-05 16:59:06

+0

的'config'文件夹(包)是在类路径中,它已经包含'application.yml',这是正确的回升和在应用程序中成功使用。 – micpalmia 2015-02-05 17:03:25

+0

你可以把xml文件放在'src/main/resources'中,然后试着让我们缩小这个问题的范围吗? – Mithun 2015-02-05 17:31:10

回答

14

正如Spring reference documentation规定,logging.config属性不能被应用程序属性中设置,因为日志已经被初始化后,他们被读取。

的解决方案是提供路径到外部日志记录配置是这样的:

java -Dlogging.config='/path/to/log4j2.xml' -jar app-current.jar 
1

micpalmia答案是绝对正确的。

我需要将配置放在classpath之外我不想将配置文件作为参数传递。所以我把一个很简单的日志记录配置在classpath资源和有春天启动应用程序重新配置后开始记录,像这样:

@SpringBootApplication 
public class Application implements CommandLineRunner { 
    public static void main(String[] args) throws Exception { 
     SpringApplication.run(Application.class, args); 
    } 

    @Override 
    public void run(String... param) throws UnsupportedEncodingException { 
     Configurator.initialize(null, "config/log4j2.xml"); 
     // ... 
    } 
} 

这种方法有显著的缺点:整个应用程序启动过程中会不会被记录为外部配置。但是,一旦定制代码运行,记录器按预期工作。虽然你可能不会,但我认为这是一种我可以忍受的妥协方式。

1

我在我的项目中有同样的问题,除了log4j2.xml我还需要类路径中的其他配置文件。 这里是我的2个解决方案的工作原理:

Soluation 1:org.springframework.boot.loader.JarLauncher

java -classpath SpringBootProject.jar;./config org.springframework.boot.loader.JarLauncher 

解决方案2春天开始启动应用程序:写 './config中' 类路径项在罐子里的MANIFEST.MF中

<build> 
    <plugins> 
     <plugin> 
     <artifactId>maven-jar-plugin</artifactId> 
     <configuration> 
      <archive> 
      <manifestEntries> 
       <Class-Path>./config/</Class-Path> 
      </manifestEntries> 
      </archive> 
     </configuration> 
     </plugin> 
     <plugin> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-maven-plugin</artifactId> 
     <version>1.5.3.RELEASE</version> 
     <executions> 
      <execution> 
      <goals> 
       <goal>repackage</goal> 
      </goals> 
      </execution> 
     </executions> 
     </plugin> 
    </plugins> 
    </build>