Search code examples
javaconfigurationlog4jlog4j2lookup

Nested lookup and substitute System properties in log4j2 properties file


In log4j2.properties file we have following definition to accept dynamic file path via System property log.filePath

appender.file.fileName=${sys:log.filePath}

In JAVA layer before creation of Logger instance we are replacing log.filePath System property with actual value

System.setProperty("log.filePath" + logfilePath);

We would like to ensure if System property log.filePath is not available/replaced, then want to create the log file in java.io.tmpdir directory with name app.log.

As per Log4j2 System Properties Lookup doc https://logging.apache.org/log4j/2.x/manual/lookups.html following syntax exists fileName="${sys:logPath:-/var/logs}/app.log" to create default log in /var/logs/app.log

Considering both Unix and Windows environment we would like to use java.io.tmpdir System property instead of /var/logs directory

I have tried multiple combination of following syntaxes but not works

fileName="${sys:logPath:-sys:java.io.tmpdir}/app.log"

Can someone please suggest if using a System property for lookup default value is supported?


Solution

  • The fallback value after :- is treated as a literal, but accepts nested lookups. So you have two choices:

    • use ${sys:logPath:-${sys:java.io.tmpdir}},
    • or define a configuration property named logPath (the default fallback for ${sys:logPath} is ${logPath}):
      <Properties>
        <Property name="logPath" value="${sys:java.io.tmpdir}"/>
      </Properties>
      <Appenders>
        <File fileName="${sys:logPath}/app.log" .../>
      </Appenders>