How to prevent logback/slf4j from parsing a new li

2019-04-15 00:50发布

问题:

I'm using logback with SLF4j for logging in my application. I have a string that contains a new line character. It is part of the string value but doesn't signify a new line. When I print the string, logback prints it in a new line. How to prevent this ?

Code:

String str = "george\nmason"
logger.info(str);

Logback pattern:

<pattern>[%d{dd MMM yyyy HH:mm:ss,SSS}] [%5p] [%X{sid}] [%-20C{0} %25M]:[%-4L] - %m%n</pattern>

Expected:

[19 Feb 2015 20:19:27] [ INFO] [] [myClass myMethod]:[52  ] - george\nmason

Actual Output:

[19 Feb 2015 20:19:27] [ INFO] [] [myClass myMethod]:[52  ] - george
mason

回答1:

You could add a replace option to your pattern in order to replace any new-line characters from the message with something else, such as a space:

%replace(%m){'\n', ' '}

In your case, you'd like to replace \n with \\n:

<pattern>[%d{dd MMM yyyy HH:mm:ss,SSS}] [%5p] [%X{sid}] [%-20C{0} %25M]:[%-4L] - %replace(%m){'\n', '\\n'}%n</pattern>