Accessing the application properties in logback.xml
Asked Answered
E

3

35

Is it possible to access application properties of spring boot in log back xml.

application.properties

dummy.property=hello

logback.xml

${dummy.property}

This did not work.

Does any one have idea if it will work.

Ewald answered 20/4, 2016 at 12:11 Comment(0)
D
57

If you name your configuration file logback-spring.xml, rather than logback.xml, you can use <springProperty> to access properties from Spring's environment including those configured in application.properties. This is described in the documentation:

The tag allows you to surface properties from the Spring Environment for use within Logback. This can be useful if you want to access values from your application.properties file in your logback configuration. The tag works in a similar way to Logback’s standard tag, but rather than specifying a direct value you specify the source of the property (from the Environment). You can use the scope attribute if you need to store the property somewhere other than in local scope.

<springProperty scope="context" name="fluentHost" source="myapp.fluentd.host"/>
<appender name="FLUENT" class="ch.qos.logback.more.appenders.DataFluentAppender">
    <remoteHost>${fluentHost}</remoteHost>
    ...
</appender>
Discrepant answered 20/4, 2016 at 19:37 Comment(3)
I having issue with logback-spring.xml after renaming from logback.xml to logback-spring.xml. @Andy Our custom layout pattern seem override by default spring pattern layout. Any idea I pretend our custom layout but also can access to spring environment?Willywilly
@Joey Please ask a question of your own. It’s a better way to get some help.Discrepant
Shame that the springProperty tag is needed even if the variable names are identicalGrau
S
13

According to the http://logback.qos.ch/manual/configuration.html#variableSubstitution

Variables can be defined one at a time in the configuration file itself or loaded wholesale from an external properties file or an external resource.
...
The property is not declared in the configuration file, thus logback will look for it in the System properties.

Logback can use system properties or properties defined explicitely. So you need to tell logback to use application.properties file

<property resource="application.properties" />
Stevie answered 20/4, 2016 at 12:48 Comment(1)
Thank you , you have no idea how relieved I am to find this solution! (for real!)Pratique
L
1

Just add your prefix that exists in your configuration file (properties, yaml) like this line:

<springProperty scope="context" name="LOGS" source="logging.path"/>

in: logback.xml

In this case: logging.path is the prefix

Lindahl answered 5/9, 2022 at 7:49 Comment(1)
For this to work either rename logback.xml to logback-spring.xml or set logging.config in application.properties. Either way allows spring to better control logging.Vino

© 2022 - 2024 — McMap. All rights reserved.