I am using logback with spring boot and I want to upper case a custom field that I get from spring property,
<springProperty name="foo" source="app.foo"/>
<customFields>
{
"foo":"${foo}"
}
</customFields>
the logback configuration is used by multiple clients within a library
and every client have this property app.foo
(or APP_FOO
env variable) and some client have put it in lower case,
that's why I want to do the field transformation within the logback config
Using ClassicConverter
, you can try changing the case of the property value.
Here is the sample logback-spring.xml
with both examples of ch.qos.logback.core.ConsoleAppender
and net.logstash.logback.encoder.LogstashEncoder
to refer the property as custom field.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<springProperty name="foo" source="app.foo" defaultValue="NotSet" />
<conversionRule conversionWord="toUpperCase" converterClass="com.example.logback_custom_fields.UpperCaseConverter"/>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<provider class="net.logstash.logback.composite.loggingevent.LoggingEventPatternJsonProvider">
<pattern>
{
"foo": "%toUpperCase{${foo}}"
}
</pattern>
</provider>
</encoder>
</appender>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%-4relative [%thread] %-5level %logger{35} -%kvp- %msg %toUpperCase{${foo}}%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="CONSOLE" />
<appender-ref ref="STDOUT" />
</root>
</configuration>
Below is the UpperCaseConverter.java
.
package com.example.logback_custom_fields;
import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
public class UpperCaseConverter extends ClassicConverter {
@Override
public String convert(ILoggingEvent event) {
String arg = getFirstOption();
if (arg == null) {
return "NOT_SET";
}
// Use the argument in your conversion logic
return arg.toUpperCase();
}
}
Example repo where you can test this is at https://github.com/imran9m/logback-custom-fields
Once you run mvn clean install
, it should execute test cases where it will populate app.foo
value in uppercase like below.
{"@timestamp":"2025-01-18T22:34:27.727725475-05:00","@version":"1","message":"Tomcat started on port 39167 (http) with context path '/'","logger_name":"org.springframework.boot.web.embedded.tomcat.TomcatWebServer","thread_name":"main","level":"INFO","level_value":20000,"foo":"APPFOOPROPVALUE"}
5030 [main] INFO o.s.b.w.e.tomcat.TomcatWebServer -- Tomcat started on port 39167 (http) with context path '/' APPFOOPROPVALUE