How can I configure logback conditionally based on context name?

In case this helps anyone else, this is how I set up conditional logback configuration with a property that can contain multiple appenders:

<root level="${logback.loglevel}">
    <if condition='isDefined("logback.appenders")'>
        <then>
            <if condition='property("logback.appenders").contains("CONSOLE")'>
                <then>
                    <appender-ref ref="CONSOLE"/>
                </then>
            </if>
            <if condition='property("logback.appenders").contains("FILE")'>
                <then>
                    <appender-ref ref="FILE"/>
                </then>
            </if>
            <if condition='property("logback.appenders").contains("GELF")'>
                <then>
                    <appender-ref ref="GELF"/>
                </then>
            </if>
        </then>
        <else>
            <appender-ref ref="CONSOLE"/>
        </else>
    </if>
</root>

The documentation is a bit spare for advanced configuration, but I found that you can use the logback context name as a variable with conditional logging. So for each project I define a custom context name in the projects logback.xml file:

<contextName>project1</contextName>

etc...

Then in my ~/loggingConfig.xml file I can do this:

<property name="appender" value="file" />

<!--if condition='property("CONTEXT_NAME").equalsIgnoreCase("project1")'>
    <then>
        <property name="appender" value="file" />
    </then>
</if-->
<if condition='property("CONTEXT_NAME").equalsIgnoreCase("project2")'>
    <then>
        <property name="appender" value="console" />
    </then>
</if>
<if condition='property("CONTEXT_NAME").equalsIgnoreCase("project3")'>
    <then>
        <property name="appender" value="file" />
    </then>
</if>

This can get a bit clunky, but in reality I am using this solution to configure properties used by a single appender for different projects, while still having a graceful fallback to a default value for projects that don't have their own conditional block.

Tags:

Logback