15

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?

Martin Schröder
  • 4,176
  • 7
  • 47
  • 81
Jatin
  • 14,112
  • 16
  • 49
  • 78

4 Answers4

23

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/:?]
slyfox
  • 950
  • 9
  • 22
9

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.

mkobit
  • 43,979
  • 12
  • 156
  • 150
Dimitar II
  • 2,299
  • 32
  • 33
  • I use logback and running into the same issue.Do you know if there is any parameter to avoid printing twice on loghost when using logback? – Kumar Apr 29 '20 at 19:38
1

Use includeStacktrace for JsonLayout

        <JsonLayout complete="false" compact="false" includeStacktrace="false">
        </JsonLayout>
Hett
  • 3,484
  • 2
  • 34
  • 51
0

Set alwaysWriteExceptions attribute of pattern layout to false.

https://logging.apache.org/log4j/2.x/manual/layouts.html#PatternLayout

Write your own exception converter that will format the exception as you wish.

https://logging.apache.org/log4j/2.x/manual/extending.html#PatternConverters

And add your pattern key to the pattern of pattern layout.

alan7678
  • 2,223
  • 17
  • 29
  • seems like `alwaysWriteExceptions` will not write stacktrace, which is not the behaviour I want. From the docs, _"Setting this to false disables this behavior and allows you to exclude exceptions from your pattern output."_ Also, I am _not_ using `PatternLayout`, so not sure if I can use PatternConverter also. – Jatin Mar 08 '16 at 07:24
  • Always writes exceptions adds a default converter to the end of the log pattern. What kind of layout are you using? – alan7678 Mar 08 '16 at 14:09