11

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
  • 44,936
  • 9
  • 114
  • 120
kheraud
  • 5,048
  • 7
  • 46
  • 75

1 Answers1

17

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.

glytching
  • 44,936
  • 9
  • 114
  • 120