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.