Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format stacktrace in log4j2?

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?

like image 367
Jatin Avatar asked Mar 04 '16 06:03

Jatin


2 Answers

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.

like image 100
Dimitar II Avatar answered Sep 25 '22 01:09

Dimitar II


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/:?]
like image 20
slyfox Avatar answered Sep 22 '22 01:09

slyfox