How to format stacktrace in log4j2?

不问归期 提交于 2020-06-11 01:56:28

问题


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?


回答1:


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/:?]



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/35789511/how-to-format-stacktrace-in-log4j2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!