logginglogback

How to use a variable to set the root log level in logback.xml?


I am trying to use an environment variable as ROOT_LOG_LEVEL to control the root log level for a project that uses a logback.xml configuration file.

<configuration>
  <!-- You can override these with environment variables -->
  <variable name="ROOT_LOG_LEVEL" value="$ROOT_LOG_LEVEL:-INFO" />
  <variable name="EXAMPLE_LOG_LEVEL" value="$EXAMPLE_LOG_LEVEL:-INFO" />

  <logger name="com.example" level="$EXAMPLE_LOG_LEVEL" />

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%level - %message</pattern>
    </encoder>
  </appender>

  <root level="$ROOT_LOG_LEVEL">
    <appender-ref ref="STDOUT" />
  </root>

</configuration>

With this configuration, I can set the log level for package com.example by either setting the environment variable (e.g. EXAMPLE_LOG_LEVEL=TRACE), or by not setting the variable and falling back to the default INFO.

While this works for com.example, it does not work for the root logger. When I try to use a variable in level="$ROOT_LOG_LEVEL", it falls back to the internal default DEBUG regardless of the contents of the variable. Only if I replace $ROOT_LOG_LEVEL by an explicit value like INFO, the root logger is changed.

Is there a way to set the root log level based on a variable?


Solution

  • Apparently, the answer to my question is that Logback does not accept variables like this:

    <variable name="ROOT_LOG_LEVEL" value="$ROOT_LOG_LEVEL:-INFO" />
    <root level="$ROOT_LOG_LEVEL">
    

    Instead, use:

    <variable name="ROOT_LOG_LEVEL" value="${ROOT_LOG_LEVEL:-INFO}" />
    <root level="${ROOT_LOG_LEVEL}">
    

    That works! Note that the :-INFO must be inside the braces.