log4j: create log file only is environment variable is set

Viewed 18

I have a log4j file where I create a new log file. However, I want this file to be created only if a particular environment variable (FEATURE_FLAG) is set.Else I don't want the log file to be created at all.

I looked this up a bit and wrote the following filter in the log4j xml file:

<logger name="MyLogger" level="INFO" additivity="false">
        <AppenderRef ref="MyLogger">
        <ScriptFilter onMatch="ACCEPT" onMisMatch="DENY">
      <Script language="groovy"><![CDATA[
         return System.getProperty("FEATURE_FLAG", "0").equalsIgnoreCase("0");
      ]]></Script>
    </ScriptFilter>
    </AppenderRef>
    </logger>

However, when I run this, I still see that the log file is created. Though nothing is written to it if the FEATURE_FLAG is not set to 0.

What I want though is: the file should not even be created if the FEATURE_FLAG is not enabled.

Please suggest. TIA. Omi

1 Answers

It seems you are willing to set a system property FEATURE_FLAG to turn on/off your logging.

How about using the system property log4j2.configurationFile (see documentation)? Then you can have multiple configuration files. One of those with no FileAppender will definitely not create any logfile. In addition you still have opportunity to send the messages to e.g. stdout or via the network.

Related