24

Is it possible to make parts of logbacks pattern layout depending on an attribute? e.g. show bdid (...) just in the case when %X{bdid} exists?

This appender

<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
        <pattern>bdid\(%X{bdid}\) - %d{HH:mm:ss.SSS} %msg%n</pattern>
    </encoder>
</appender>

prints

bdid(0b5d3877-f3dd-4189-8b1b-489c8b617f2a) 18:22:25.206 if bdid exists, but prints

bdid() 18:22:20.928 if it doesn't.

How do I omit the empty bdid() in my log?

4

1 に答える 1

17

You can use the replace function, details are in the docs here. A working example is the following:

logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%replace(bdid\(%X{bdid}\)){'bdid\(\)', ''} - %d{HH:mm:ss.SSS} %msg%n</pattern>
    </encoder>
  </appender>
  <root level="DEBUG">
    <appender-ref ref="STDOUT" />
  </root>

</configuration>

Test Function

public class PatternTest
{
  @Test
  public void test()
  {
    Logger logger = LoggerFactory.getLogger(PatternTest.class);
    MDC.put("bdid", "hola");
    logger.info("Check enclosed.");
    MDC.remove("bdid");
    logger.info("Check enclosed.");
  }
}

Test output

bdid(hola) - 18:40:40.233 Check enclosed.
 - 18:40:40.234 Check enclosed.
于 2018-02-13T02:54:53.370 に答える