Logback configuration to have exceptions on a single line?

kheraud :

My logs are extracted, piped and consolidated into elasticsearch. Multiline events are hard to track and diagnose.

Instead of playing with collectors and regular expressions to group exception lines in a single record, is there a way with logback configuration to have Exception stacktrace on a single line ?

glytching :

You can declare a conversion rule in your logback.xml for the %ex symbolic like so:

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
    <conversionRule conversionWord="ex" converterClass="com.foo.CompressedStackTraceConverter" /> 

    ...

</configuration>

Then declare CompressedStackTraceConverter like so:

import ch.qos.logback.classic.pattern.ThrowableProxyConverter;
import ch.qos.logback.classic.spi.IThrowableProxy;

public class CompressedStackTraceConverter extends ThrowableProxyConverter {
    @Override
    protected String throwableProxyToString(IThrowableProxy tp) {
        String original = super.throwableProxyToString(tp);

        // replace the new line characters with something, 
        // use your own replacement value here
        return original.replaceAll("\n", " ~~ ");
    }
}

This custom conversion specifier will work as long as your logging pattern contains the %ex symbolic. For example, a pattern like this:

<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
    <pattern>%d{yyyy-MM-dd HH:mm:ss}|%-5level|%logger{36}|%msg %ex %n</pattern>
</encoder>

If your pattern does not include the %ex symbolic then the stacktrace is part of the %msg in which case you would declare the conversion rule like this ...

<conversionRule conversionWord="msg" converterClass="com.foo.CompressedStackTraceConverter" /> 

... though this would have the effect of applying the CompressedStackTraceConverter to your entire log message, not just to the stack trace portion of it.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=476655&siteId=1