javalogbackappenderjanino

Logback conditional ("isDefined") appender creation not working


I have something like the following in my logback.xml (I've simplified it down to just the relevant parts):

  <if condition='isDefined("REQUEST_LOG_DIR")'>
    <then>
      <appender name="requests" class="ch.qos.logback.core.FileAppender">
        <file>${REQUEST_LOG_DIR}/requests.log</file>
        <encoder><pattern>%msg%n</pattern></encoder>
      </appender>
    </then>
  </if>

  <logger name="application.requests" additivity="false" level="INFO">
    <if condition='isDefined("REQUEST_LOG_DIR")'>
      <then>
          <appender-ref ref="requests" />
      </then>
    </if>
  </logger>

If I run my application with REQUEST_LOG_DIR defined, it works as expected: Messages I log to this logger end up in ${REQUEST_LOG_DIR}/requests.log.

However, if I run with my application with REQUEST_LOG_DIR undefined, it ends up creating a REQUEST_LOG_DIR_IS_UNDEFINED directory containing an empty requests.log file.

The fact that the file stays empty indicates that the second piece of conditional logic is working as expected to not add the appender to the logger when REQUEST_LOG_DIR is undefined.

However, I don't understand why the directory is getting created. If REQUEST_LOG_DIR is undefined (which it obviously is, given the name of the directory), then the first conditional should be stopping the FileAppender from being instantiated.


Solution

  • That FileAppender is not lazy. There are ways to work around that, partially.

    You can wrap your file into :

     <appender name="wrapper" class="ch.qos.logback.classic.sift.SiftingAppender">
    
      ....
    

    I remember that there were cases where I did not liked this, but can't remember anymore now.