Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make logback pattern part optional?

Tags:

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?

like image 258
Stefan K. Avatar asked Oct 12 '15 16:10

Stefan K.


People also ask

How do I specify the path for Logback xml?

You may specify the location of the default configuration file with a system property named "logback. configurationFile". The value of this property can be a URL, a resource on the class path or a path to a file external to the application.

How do you specify Logback xml in application properties?

xml , you can use <springProperty> to access properties from Spring's environment including those configured in application. properties . This is described in the documentation: The tag allows you to surface properties from the Spring Environment for use within Logback.

Does Logback use SLF4J?

Logback natively implements the SLF4J API.


1 Answers

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. 
like image 117
ilooner Avatar answered Oct 04 '22 12:10

ilooner