Search code examples
springspring-bootlogback

Setting logback property via spring config + environment variable in spring config


I want to configure logback in such way that some specific appender will work only if system variable LOGGER_ENABLED is set to true. If the variable is not set at all it should not give any error. So I tried several approaches 1. Set only env variable and use it in logback as

<if condition='${LOGGER_ENABLED}'>
    <then>
        <appender-ref ref="MyAppender"/>
    </then>
</if>

it works fine if variable is set to true of false. If it is absent - it throws error like ...is undefined 2. Another catch is to use spring yml file and set it like

sendErrors=${LOGGER_ENABLED:false} //that means to use false if not set

and in logback to use like

<if condition='${sendErrors}'>
    <then>
        <appender-ref ref="MyAppender"/>
    </then>
</if>

in such way it will work only for static "false" or "true" values and do not prefetch ${LOGGER_ENABLED:false} condition.

Is it possible to perform such configuraiton with spring boot and logback?


Solution

  • Ok, I found the answer on my question. In logback file default separator is ":-" instead of ":" in general spring boot file. After replacing separator to ":-" I'm able to specify default value exactly in logback file Example

    <if condition='${sendErrors:-true}'>
        <then>
            <appender-ref ref="MyAppender"/>
        </then>
    </if>