I'm using Log4j2 and its JSONLayout
to produce logs in JSON format. Everything works fine but when I use Logger.warn(String message, Throwable t)
like:
l4j2Logger.warn("log1...\n...log2", new Exception("ex1...\n...ex2"));
I get in my logs:
"message":"log1...\n...log2",
"throwable":"java.lang.Exception: ex1...\\n...ex2\\n\tat test.Test.log(Test.java:73)\\n\tat......"
In the message
key, the \\n
character is written \\n
in the log file,
but in the throwable
key, the \\n
character is written \\\\n
in the log file.
As I need to parse these logs, the JSON parser doesn't like \\\\n
, which seems normal since the JSON specifications indicates that \\n
shall be used.
Here is an extract of my log4j XML configuration file:
<Appenders>
<File name="FileAppender" fileName="log4j2.log" append="true">
<JSONLayout complete="true" compact="false"/>
</File>
</Appenders>
Do you know why Log4j2 is using \\\\n
in throwable
, and if/how I can change that? (I'm using Log4j-2.0-RC1, the latest at this time)
First, be careful interpreting log files. Whatever prints the log files might insert escape sequences.
While parsing a string in a JSON document, \\n will be replaced with a newline character. \\n is perfectly legal though: The \\ character will be replaced with a single \\, and then you just have an ordinary n. So instead of a string with a newline character, you get a string with a backslash character followed by an n character delivered by the parser. The parser shouldn't have any problems with that.
In your l4j2Logger.warn, you use two strings containing newline characters. It seems that in the JSON document, "message" has a string value that represents the first argument. The "throwable" value seems has a string value that represents source code. The line in your log file is:
"throwable":"java.lang.Exception: ex1...\\n...ex2\\n\tat test.Test.log(Test.java:73)\\n\tat......"
This will be parsed as the string
java.lang.Exception: ex1...\n...ex2\n at test.Test.log(Test.java:73)\n at......"
I'd check what tools read these log files; this seems to be intended.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.