Kojotak
Kojotak

Reputation: 2070

How to limit number of stacktrace lines from nested Exceptions

Lets have an Exception stacktrace with multiple 'caused by' sections:

my.Exception1: Bad luck
  at ...
Caused by: my.Exception2
  at ...
Caused by: my.Exception3
  at ...
Caused by: my.Exception4
  at ...

each caused by section can span multiple lines. There is a JVM parameter

-XX:MaxJavaStackTraceDepth

but this affects the stacktrace as a whole - it will cut everything below for example Exception3 (the inner most Exception will be out). I would like to keep every 'caused by' section, but limit each part to for example 20 lines. One possible solution I'm aware of is ThrowableRenderer from log4j. Is there something else? The goal is to preserve as much useful information from stacktraces as possible in an limited environment (maximum size in bytes for one log entry).

Upvotes: 2

Views: 3343

Answers (1)

jmehrens
jmehrens

Reputation: 11045

ThrowableRenderer would be the way to go. There is also the FilteredPatternLayout from openutils-log4j.

The heavy handed approach would be to get the throwable stacktrace, filter out frames, and reassign the filtered stacktrace for each throwable in the cause chain before you log the exception chain. Which could be applied in a custom log filter class but that is bending the rules a bit because the filter shouldn't really modify the throwable chain. Those frames would be lost forever so there would be risk there.

Logback has support for filtering of stackframes. See also Filtering the Stack Trace From Hell for some ideas on what information is worth keeping.

Upvotes: 3

Related Questions