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

log4j2 configuration
log4j2 properties
log4j2 not writing to file
log4j2 programmatic configuration
log4j jdbc appender
log4j2 not creating log file
log4j2 set log level
log4j2 smtpappender example

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" />

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" />

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.

Similar to rgoers solution but using nashorn instead of groovy. This solution benefits from fact that Nashorn engine is part of Java 8 so there is no additional dependencies needed.

  <Script name="isAppender2Enabled" language="nashorn"><![CDATA[
    var System = Java.type('java.lang.System'),
        Boolean = Java.type('java.lang.Boolean');
    Boolean.parseBoolean(System.getProperty('enableAppender2', 'false'));

  <Logger name="myLogger" level="info" additivity="false">
    <AppenderRef ref="myAppender1" />
    <AppenderRef ref="myAppender2">
      <ScriptFilter onMatch="ACCEPT" onMisMatch="DENY">
        <ScriptRef ref="isAppender2Enabled" />

Note that ScriptFilter is evaluating the script every time when Log4j event occurs. Therefore it is possible to enable/disable the appender on the run time (by changing the value of the system property) with immediate effect. On the other hand, script evaluation can have negative impact on logging performance.

Log4j2: how to get a conditional appender without any code, Log4j2 does not have a conditional feature so if you need to use an appender depending some environment variable or system property it Here is how we can configure it for our use case: Back to Java/EE/Microprofile. Given log4j2.xml is reference to configure multiple appenders such as console appender and file appenders. This also configure the dynamic log root path. Log4j multiple appenders configuration Sample log4j configuration is given blow. It does following things: Uses dynamic log root path where log files will be created. Pass environment variable as -DAPP_LOG_ROOT=c:/temp to configure […]

Solution without any scripting:

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

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

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

        <Root level="info">
            <AppenderRef ref="${appenderToUse}"/>

How to conditionally enable/disable a Log4J2 appender , java -jar app.jar >/dev/null 2>&1. But this would suppress all console Another option is to conditionally disable a given appender. To do this, first we need a Just add the dependency to your project: Listing 1. build.gradle CDATA[ return System.getProperty("CONSOLE_APPENDER_ENABLED", 'true'). Like any other Java properties file, a file is a set of key-value pairs with options to configure the various components of Log4J 2, such as loggers, appenders, and layouts. A

Log4j – Frequently Asked Questions, How do I configure log4j2 in code without a configuration file? How do I How do I send log messages with different levels to different appenders? You can also specify the full path of the configuration file with this system property: -Dlog4j​. The Log4j 2 API has support for Java 8 lambda expressions. Any logging application intended to print logging information to a console should use this org.apache.log4j.ConsoleAppender. ConsoleAppender is a very simple class designed to write logging information to either System.out or System.err. The destination of the log messages can be configured via a property named target. Properties of ConsoleAppender The configurable properties of

I wasn't able to figure out a solution via config file alone, but I found one that solves the problem programmatically.

Note that in our specific case, we always log to a "local log" ("splunk local"), but in given cases (controlled by the property), we also want to log the same information to another location (that is not relative) and is periodically read and forwarded to a splunk server ("splunk forwarder").

And that's why we can copy most of the properties from one logger to the other.

private static final Logger SPLUNK_LOG = getLogger();

private static Logger getLogger() {
    if (!BooleanUtils.toBoolean(SystemUtils.getJavaPropertyValue(ENABLE_PROPERTY_NAME, "false"))) {
        return LoggerFactory.getLogger(SPLUNK_LOG_NAME);
    } else {"Dynamically adding splunk forwarder appender");
        try {
            final LoggerContext loggerContext = (LoggerContext) LogManager.getContext();
            final Configuration configuration = loggerContext.getConfiguration();

            // configure appender based on local splunk appender
            final RollingFileAppender splunkLocal = (RollingFileAppender) configuration.getAppender(LOCAL_LOG_NAME);
            final RollingFileAppender splunkForwarder = RollingFileAppender.createAppender(FORWARDER_FILE_NAME,
                    splunkLocal.getManager().getTriggeringPolicy(), splunkLocal.getManager().getRolloverStrategy(),
                    splunkLocal.getLayout(), splunkLocal.getFilter(), null, FORWARDER_ADVERTISE, null, null);

            // add splunk forwarder appender to splunk logger
            final LoggerConfig loggerConfig = configuration.getLoggerConfig(SPLUNK_LOG_NAME);
            loggerConfig.addAppender(splunkForwarder, Level.INFO, null);

  "Successfully added splunk forwarder appender");
            return loggerContext.getLogger(SPLUNK_LOG_NAME);
        } catch (Exception ex) {
            throw new IllegalStateException("Failed to dynamically add splunk forwarder appender", ex);

If anyone knows how to do this via config file alone, that would be great.

xml conditional code in log4j2.xml - xml - html, My intention is to create separate paths for logging, based on the operating goal of having a different paths for e.g. different OSs by using a system property for You can conditionally add appenders in Log4j2 I had done it the following way. your node to the custom logging file when starting the node (e.g. java -​Dlog4j. Typically, the steps to use log4j in your Java application are as follows: Download latest log4j distribution. Add log4j’s jar library into your program’s classpath. Create log4j’s configuration.

The way this is intended to be handled is by using a filter. In this case you can use a Script filter.

<Logger name="myLogger" level="info" additivity="false">
  <AppenderRef ref="myAppender1" />
  <AppenderRef ref="myAppender2">
     <ScriptFilter onMatch="ACCEPT" onMisMatch="DENY">
      <Script language="groovy"><![CDATA[
         return System.getProperty("enableAppender2", "false").equalsIgnoreCase("true");

log4j – How do I conditionally add log4j2 appender depending on , add log4j2 appender depending on java system property? configure appender based on local splunk appender final RollingFileAppender  How this works varies depending on whether your application is a Servlet 3.0 or newer or Servlet 2.5 web application. In either case, you'll need to add the log4j-web module to your deployment as detailed in the Maven, Ivy, and Gradle Artifacts manual page.

Configuring Logging, You can configure these properties using the $MULE_HOME/conf/log4j2.xml file, which file to include a new Log4j 2 Appender called mule-agent-appender . Log4j will inspect the "log4j.configurationFile" system property and, if set, will attempt to load the configuration using the ConfigurationFactory that matches the file extension. If no system property is set the properties ConfigurationFactory will look for in the classpath.

Variable substitution · The logback manual, Java system properties can be set on the command line as shown next: <​configuration> <appender name="FILE" class="ch.qos.logback.core. Note that conditional processing requires the Janino library. Note that the <contextName​> directive sets the context name based on the value of the appName property  Log4j comes with several appenders that do things like console and file output and send logging messages using email or JMS (Java Message Service). Log4j also includes a socket-based appender

Spring Boot Features, If you use environment variables rather than system properties, most Default configurations are provided for Java Util Logging, Log4J2, and Logback. In each​  Referencing of logger from LogManager has started Log4j system. Log4j will inspect log4j.configurationFile system property to determine log4j2 configuration file. Log4j configuration can be written in JSON, YAML and XML. We can set log4j.configurationFile system property through System.setProperties("log4j.configurationFile","FILE_PATH") or by passing it as a JVM parameter like you see in the figure below. Notice also File protocol prefix.

  • WARNING: The Nashorn JavaScript engine is marked as deprecated in Java 11 - see tweets from Mark Reinhold: Following warning is produced in Java 11: Warning: Nashorn engine is planned to be removed from a future JDK release. You can use JVM option to prevent printing of the warning: -Dnashorn.args="--no-deprecation-warning".
  • In conjuction with NullAppender, this solution makes me happy - now I can turn on/off Console appender when I want!