By default log4j2 prints stacktrace on multiple lines, separated by newline
characters. Something like:
java.lang.NullPointerException: error enovountered
at ...
at ...
at ...
I want my stacktrace on a single line, something like, essentially using |
as a delimiter rather than \n
java.lang.NullPointerException: error enovountered at ... | at ... | at ...
How will I accomplish something like this in log4j2?
The answers above contain the recipe. Here I am adding example:
<PatternLayout>
<alwaysWriteExceptions>false</alwaysWriteExceptions>
<pattern>%level;%d{yyyy-MM-dd HH:mm:ss.SSS};%t;%c;%enc{%msg}{CRLF};%replace{%ex}{[\r\n]{1,2}}{|}%n</pattern>
</PatternLayout>
If you skip the alwaysWriteExceptions
parameter, the stack will appear twice - once linearized and once as multi-line.
As the PatternLayout
documentation specifies, the %throwable
family of conversion keys actually support being able to change the separator used for individual stack trace elements, as well as the "cause" exceptions.
Given a pattern like:
[%threadName] %-5level %logger{36} - %message{nolookups}%xThrowable{separator(|)}%n
You'll get output like:
[main] ERROR my.cool.Application - Catching java.lang.RuntimeException: I'm wrapping the NPE| at my.cool.Application.main(Application.java:24) [main/:?]|Caused by: java.lang.NullPointerException: This is a forced NPE| at java.util.Objects.requireNonNull(Objects.java:228) ~[?:1.8.0_121]| at my.cool.Application.main(Application.java:21) ~[main/:?]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With