I'm trying to remove newline from Java stacktraces.
I've following logback pattern -
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %replace(%msg){'\n', ''}%n</pattern>
I expect it to replace newlines in messages but it is not doing so. I see stacktraces printed out with newlines.
However, if I use following pattern (for testing purpose only)-
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %replace(%msg){'.*', 'x'}%n</pattern>
I find that messages are getting replaced with character x but stack traces are still getting printed as is.
This makes me believe that logback treats stacktraces indepdentantly. I've gone through the logback documentation it says that one can refer to stacktraes via (%ex).
But then, I can have only one pattern active at a time for the appender. How do I go about making sure that I don't get newline in stacktraces?
After looking at how Logback formatter builds the string on my Windows box, I saw that the stack trace contains \r\n
for each new line, so if you are using Windows, try this instead:
<pattern>........ %replace(%ex){'[\r\n]+', '\\n'}%nopex%n</pattern>
Explanations:
\r\n
: At first I tried with only %replace(%ex){'\n', 'X'}
but then I had in the logs the new line character then a 'X'. Instead, using %replace(%ex){'[\r\n]+', ''}
removes all occurrences of \r
and \n
. If you want to display the string "\n"
to indicate that a new line was here, you can add '\\n'
in the %replace
second parameter.
%nopex
: I don't know why, but if you use %replace
on %ex
, Logback adds a second stack trace to your entry, this time with all the new lines. Using %nopex
(see documentation), it will suppress this second stack by faking the use of an actual stack without any %replace
.
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