4

I'm trying to use spring property values in logback.xml.

The file application-dev.properties (which is part of my jar) contains the property:

myapp.test.appender-class=ch.qos.logback.core.ConsoleAppender

and I added the following in the logback.xml:

<configuration scan="true" debug="true">
    <property resource="application-dev.properties" />
    <appender name="consoleAppender" class="${myapp.test.appender-class}">

When my application starts, I'm getting the following error:

ERROR in ch.qos.logback.core.joran.action.AppenderAction - Could not create an Appender of type [${appender-class}]. ch.qos.logback.core.util.DynamicClassLoadingException: Failed to instantiate type ${myapp.test.appender-class}

What am I doing wrong?

Note: I also tried to rename my logback.xml to logback-spring.xml, but this creates other problems.

gillyn
  • 51
  • 1
  • 3

2 Answers2

3

Try using springProperty

<configuration>
    <springProperty name="my_appender" source="myapp.test.appender-class"/>

    <appender name="consoleAppender" class="${my_appender}"/>
</configuration>
Ermintar
  • 1,322
  • 3
  • 22
  • 39
  • Note: using springProperty requires also to change logback.xml to logback-spring.xml. I did that and got the same error: `Could not create an Appender of type [${my_appender}]. ch.qos.logback.core.util.DynamicClassLoadingException: Failed to instantiate type ${my_appender}` – gillyn Dec 12 '18 at 10:33
  • There's a chance that logback implementation doesn't expext an expression instead of a class for class=. Do other properties get autowied (like level or remoteHost from example above)? – Ermintar Dec 12 '18 at 11:25
  • 1
    Youre' right @Ermintar ! The class doesn't accept a variable, but other attributes do. Very strange, because the value is just a string. Thanks. – gillyn Dec 12 '18 at 12:34
3

According to the official docs

Because the standard logback.xml configuration file is loaded too early, you cannot use extensions in it. You need to either use logback-spring.xml or define a logging.config property.

And to cope up with this, Spring provides <springProperty> tag.

The tag lets you expose properties from the Spring Environment for use within Logback. Doing so 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. However, rather than specifying a direct value, you specify the source of the property (from the Environment). If you need to store the property somewhere other than in local scope, you can use the scope attribute.

<springProperty scope="context" name="fluentHost" source="myapp.fluentd.host" defaultValue="localhost"/>
<appender name="FLUENT" class="ch.qos.logback.more.appenders.DataFluentAppender">
    <remoteHost>${fluentHost}</remoteHost>
    ...
</appender>
Abdullah Khan
  • 12,010
  • 6
  • 65
  • 78