Slf4j, logback - removing mdc tag from json
Asked Answered
T

2

6

I am adding some context info to log records using MDC:

MDC.put("Correlation-ID", UUID.randomUUID().toString()); 

I am using following logback encoder:

    <encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
        <layout class="ch.qos.logback.contrib.json.classic.JsonLayout">
            <timestampFormat>yyyy-MM-dd'T'HH:mm:ss.SSSX</timestampFormat>
            <timestampFormatTimezoneId>Etc/UTC</timestampFormatTimezoneId>
            <appendLineSeparator>true</appendLineSeparator>

            <jsonFormatter class="ch.qos.logback.contrib.jackson.JacksonJsonFormatter">
                <prettyPrint>false</prettyPrint>
            </jsonFormatter>
        </layout>
    </encoder> 

I've got following log:

{"timestamp":"2020-01-20T11:40:09.850Z","level":"INFO","thread":"main","mdc":{"Correlation-ID":"66f7843c-9855-450d-ad97-b1c78404f051"},"logger":"liquibase.Liquibase"...

I would like to remove root mdc tag to get:

{"timestamp":"2020-01-20T11:40:09.850Z","level":"INFO","thread":"main","Correlation-ID":"66f7843c-9855-450d-ad97-b1c78404f051","logger":"liquibase.Liquibase"...

How would I achive this?

Treenatreenail answered 20/1, 2020 at 12:1 Comment(1)
Log4j allows getting these variables explicitly: e.g. pattern="%d{ISO8601} %-5p - %-26.26c{1} - %notEmpty{[username=%X{username}] - }%m\n" . I think logback might have something similar?Mesozoic
G
3

You could use the logstash logback JSON encoder.

Add these dependencies to your pom.xml:

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>${slf4j.version}</version>
</dependency>

<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-core</artifactId>
    <version>${logback.version}</version>
</dependency>

<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>${logback.version}</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>${jackson.version}</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>${jackson.version}</version>
</dependency>

<dependency>
    <groupId>net.logstash.logback</groupId>
    <artifactId>logstash-logback-encoder</artifactId>
    <version>${logstash.version}</version>
</dependency>

Here's a sample:

<encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
    <providers>
        <pattern>
            <omitEmptyFields>true</omitEmptyFields>
            <pattern>
                {
                    "timestamp": "%d{yyyy-MM-dd'T'HH:mm:ss.SSSZ}",
                    "level": "%level",
                    "thread": "%t",
                    "Correlation-ID": "%mdc{Correlation-ID}",
                    "logger": "%logger",
                    ...
                }
            </pattern>
        </pattern>
    </providers>
</encoder>

Documentation here.

Geronto answered 13/6, 2022 at 8:28 Comment(0)
S
0

If you want to keep the Correlation Id you can extend the JSON Layout class and set the property on the Map.

public class CustomJsonLayout extends JsonLayout {
@Override
protected Map toJsonMap(ILoggingEvent iLoggingEvent) {
    LinkedHashMap var2 = new LinkedHashMap();
    this.addTimestamp("timestamp", this.includeTimestamp, iLoggingEvent.getTimeStamp(), var2);
    this.add("level", this.includeLevel, String.valueOf(iLoggingEvent.getLevel()), var2);
    this.add("thread", this.includeThreadName, iLoggingEvent.getThreadName(), var2);
    this.add("logger", this.includeLoggerName, iLoggingEvent.getLoggerName(), var2);
    this.add("message", this.includeFormattedMessage, iLoggingEvent.getFormattedMessage(), var2);
    this.add("raw-message", this.includeMessage, iLoggingEvent.getMessage(), var2);
    this.add("context", this.includeContextName, iLoggingEvent.getLoggerContextVO().getName(), var2);
    this.addThrowableInfo("exception", this.includeException, iLoggingEvent, var2);
    this.addCustomDataToJsonMap(var2, iLoggingEvent);
    Map<String,String> mdc = iLoggingEvent.getMDCPropertyMap();
    String correlationId = mdc.getOrDefault("Correlation-ID","");
    this.add("Correlation-ID", this.includeMDC, correlationId , var2);
    return var2;
}
}

And in the layout add the new class.

 <layout class="com.test.utils.CustomJsonLayout">
Strafford answered 5/2, 2021 at 10:12 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.