Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I conditionally add log4j2 appender depending on java system property?

Tags:

java

log4j

log4j2

I'm trying to figure out how I can add an appender to a logger dependent on whether a java system property is given / set.

So let's say I have a basic configuration like this:

<Logger name="myLogger" level="info" additivity="false">
  <AppenderRef ref="myAppender1" />
  <AppenderRef ref="myAppender2" />
</Logger>

So now I'd like to figure out a way to conditionally only add the 2nd appender if I provide a parameter -PaddAppender2. Something like this:

<Logger name="myLogger" level="info" additivity="false">
  <AppenderRef ref="myAppender1" />
  <?if (${sys:enableAppender2:-false) == "true"}>
  <AppenderRef ref="myAppender2" />
  </?if> 
</Logger>

How do I do that?

I know I can for example make the level dynamic on a given property ("logLevel") like that (where "info" is the default if the property is not given):

<Logger name="test" level="${sys:logLevel:-info}" additivity="false">

I looked at the documentation for filters, and I can't figure it out. That is of course if filters are even the right way to go here.

like image 714
mac Avatar asked Jan 28 '16 07:01

mac


1 Answers

Solution without any scripting:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="error" strict="true">
    <Properties>
        <Property name="appenderToUse">stdout_${sys:LOG4J_LAYOUT:-plain}</Property>
    </Properties>

    <Appenders>
        <Appender type="Console" name="stdout_plain">
            <Layout type="PatternLayout" pattern="%d [%t] %-5p %c - %m%n"/>
        </Appender>

        <Appender type="Console" name="stdout_json">
            <Layout type="JSONLayout" compact="true" eventEol="true" stacktraceAsString="true" properties="true"/>
        </Appender>
    </Appenders>

    <Loggers>
        <Root level="info">
            <AppenderRef ref="${appenderToUse}"/>
        </Root>
    </Loggers>
</Configuration>
like image 158
sap1ens Avatar answered Oct 20 '22 08:10

sap1ens