在log4j2.xml中使用Spring Boot应用程序属性 [英] Use Spring boot application properties in log4j2.xml

查看:1325
本文介绍了在log4j2.xml中使用Spring Boot应用程序属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在基于Spring Boot的Web应用程序上工作,并希望使用log4j2作为记录器实现.
使用 log4j2-spring.xml 文件中定义的日志记录配置,一切都可以正常工作.

不起作用:我想在log4j2-spring.xml文件中使用属性占位符,该占位符应从用于配置Spring Boot的 application.yml 文件中定义的属性中解析.

这可能吗?如果是,怎么办?

解决方案

>无法通过属性占位符直接替换log4j2-spring.xml中的属性,因为log4j2-spring.xml不在Spring的管辖范围之内,并且仅用于配置目的.

但是,您可以利用Log4j2的现成属性替换功能,如

第2步-在日志配置中使用上面定义的属性,例如文件名的后缀

<Appenders>
    <File name="file" fileName="/path/to/logs/app-${someProp}.log">
        <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p %-40c{1.} - %m%n"/>
    </File>
</Appenders>

第3步-创建捆绑包(可视属性文件)以保存属性值,例如test.properties

# properties for log4j2
someKey=someValue
someKey1=someValue1

在您的情况下,此文件将包含您希望在log4j2配置中使用的yaml中的值.如果这些属性也可以在应用程序中使用,它们将在yaml中复制,并且捆绑包( ie属性文件)应该是可以接受的折衷方案,因为spring无法将其注入log4j2配置中. >

如果需要更多信息,请在评论中告知.

I am working on a web application based on spring boot and want to use log4j2 as the logger implementation.
Everything works fine with the logging configuration defined in a log4j2-spring.xml file.

What is not working: I want to use property placeholders in the log4j2-spring.xml file that should be resolved from properties defined in the application.yml file used for configuring spring boot.

Is this possible? If yes, how?

解决方案

Direct substitution of properties in log4j2-spring.xml via property placeholder is not possible as the log4j2-spring.xml is outside the ambit of Spring, and used purely for configuration purpose.

However, you can leverage the Log4j2 out-of-box feature of property substitution as outlined here.

Step 1 - Specify the property name and its variable in log4j2-spring.xml as below

<Configuration status="warn">
    <Properties>
        <Property name="someProp">${bundle:test:someKey}</Property>
    </Properties> 
    <!--other configs -->
</Configuration>

Step 2 - Use the above defined property in the log configuration e.g. suffix to log file name

<Appenders>
    <File name="file" fileName="/path/to/logs/app-${someProp}.log">
        <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p %-40c{1.} - %m%n"/>
    </File>
</Appenders>

Step 3 - Create a bundle (viz. properties file) to hold the properties value e.g. test.properties

# properties for log4j2
someKey=someValue
someKey1=someValue1

In your case this file will contain the values in yaml which you seek to use in log4j2 configuration. In case those properties are used in application as well, they will be duplicated in yaml and the bundle (i.e. properties file) which should be acceptable compromise given spring can not inject them in log4j2 configuration.

Let know in comments in case of any more information is required.

这篇关于在log4j2.xml中使用Spring Boot应用程序属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆