Make logback pattern part optional?
Asked Answered
L

1

29

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?

Lollard answered 12/10, 2015 at 16:27 Comment(0)
R
22

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.
Rexer answered 13/2, 2018 at 2:54 Comment(1)
%replace(bdid(%X{bdid})){'bdid()', ''} throws an ERROR in CompositeConverter<, children: ch.qos.logback.core.pattern.LiteralConverter@415b0b49> - at least two options are expected whereas you have declared none in spring bootPachyderm

© 2022 - 2024 — McMap. All rights reserved.