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?
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.
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.
Logback natively implements the SLF4J API.
You can use the replace function, details are in the docs here. A working example is the following:
<?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>
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."); } }
bdid(hola) - 18:40:40.233 Check enclosed. - 18:40:40.234 Check enclosed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With