如何从替代源(application.properties)获取特定 log4j2 属性的数据

问题描述 投票:0回答:1

在类路径 application.property 上有 log4j2 和 spring 属性文件的标准配置。

log4j2.xml

<Properties>
        ...
        <Property name="APP_LOG_ROOT">${bundle:application:log.root.dir}</Property>
        ...
</Properties>

应用程序属性

...
log.root.dir=/opt/tomcat/logs
...

数据已正确读入 log4j2.xml,但是如果我想在使用 Maven 创建工件时获得替代属性并放置不同的 application.property:

mvn clean install -Dapplication.properties.path=file:/some_path/application.properties

? 之后,我就可以正确读取新属性了。

@Value("${log.root.dir}")
    private String ololo;

但 log4j2 无法自行完成此操作。

spring spring-mvc log4j2
1个回答
3
投票

如果您想在 Log4j2 配置文件中使用 Spring Environment

 中的 
any 值,则需要使用 Spring Boot Lookup:

  • 对于 Spring Boot 2.x,这需要额外的依赖项:
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-spring-boot</artifactId>
        <scope>runtime</scope>
    </dependency>
    
  • 自 Spring Boot 3.x 起,查找包含在
    spring-boot
    中。

添加Spring Boot查找后,只需替换即可

${bundle:application:log.root.dir}

${spring:log.root.dir}

编辑:与作为应用程序的第一个系统之一启动的 Log4j 不同,Spring 的

Environment
仅在一段时间后才可用。

为了使查找工作:

  • 您可以按照
    Bojan
    的建议,将您的文件称为 log4j2-spring.xml
  • 或者您可以使用 Spring 仲裁器来保护使用 Spring 查找的部分(参见这个问题):
    <Select>
        <SpringProfile name="default">
            <Property name="APP_LOG_ROOT" value="${spring:log.root.dir}"/>
        </SpringProfile>
        <DefaultArbiter>
            <Property name="APP_LOG_ROOT" value="...folder for initial logs..."/>
        </DefaultArbiter>
    </Select>
    
© www.soinside.com 2019 - 2024. All rights reserved.