Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove newline from Java stacktraces in logback?

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?

like image 998
user375868 Avatar asked Jul 30 '16 01:07

user375868


1 Answers

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.

like image 141
xav Avatar answered Oct 25 '22 19:10

xav