Blessed Geek
Blessed Geek

Reputation: 21684

Conditional log4j.xml pattern

Because %C and %M are resource intensive, for the pattern

%d{yyyy-MM-dd HH:mm:ss} [%C][%M][%t]

I would like that %C and %M to be effective only if log level is set to debug (or more detailed levels).

Does log4j have any provisions for such conditional output formats?

Upvotes: 0

Views: 2498

Answers (2)

DMunz
DMunz

Reputation: 253

Similar to what Matt suggested before, you can also attach filters to log Appenders and attach multiple Appenders to a single logger. For example:

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

<appender name="console" class="org.apache.log4j.ConsoleAppender">
    <param name="Target" value="System.out" />
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%C][%M][%t] - %m%n" />
    </layout>
    <filter class="org.apache.log4j.varia.LevelRangeFilter">
        <param name="LevelMax" value="DEBUG" />
    </filter>
</appender>

<appender name="console2" class="org.apache.log4j.ConsoleAppender">
    <param name="Target" value="System.out" />
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%t] - %m%n" />
    </layout>
    <filter class="org.apache.log4j.varia.LevelRangeFilter">
        <param name="LevelMin" value="INFO" />
    </filter>
</appender>

<root>
    <priority value="debug" />
    <appender-ref ref="console" />
    <appender-ref ref="console2" />
</root>

</log4j:configuration>

This should output the patterns you require. The max level filter on the first appender should prevent high log levels and the min level on the second appender prevents debug level statements from appearing twice.

Hope this helps.

Upvotes: 1

Matt
Matt

Reputation: 637

You could use another logger that sets additivity="false" for the debug level combined with a ThresholdFilter that only accepts DEBUG or below. It would be a bit of work, though. If that doesn't work, file an issue.

Upvotes: 0

Related Questions