简体   繁体   English

Log4j2 JSON布局:处理“ \\ n”(换行符)

[英]Log4j2 JSON layout: handling of “\n” (new line character)

I'm using Log4j2 and its JSONLayout to produce logs in JSON format. 我正在使用Log4j2及其JSONLayout来生成JSON格式的日志。 Everything works fine but when I use Logger.warn(String message, Throwable t) like: 一切正常,但是当我使用Logger.warn(String message, Throwable t)如下所示:

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, message密钥中, \\n字符写入\\n在日志文件中,
but in the throwable key, the \\n character is written \\\\n in the log file. 但是在throwable键中, \\n字符被写入\\\\n在日志文件中。

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. 由于我需要解析这些日志,因此JSON解析器不喜欢\\\\n ,这似乎很正常,因为JSON规范指示应使用\\n

Here is an extract of my log4j XML configuration file: 这是我的log4j XML配置文件的摘录:

<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? 您知道Log4j2为什么在throwable使用\\\\n以及是否/如何更改它吗? (I'm using Log4j-2.0-RC1, the latest at this time) (我正在使用最新的Log4j-2.0-RC1)

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. 在解析JSON文档中的字符串时,\\ n将被换行符替换。 \\n is perfectly legal though: The \\ character will be replaced with a single \\, and then you just have an ordinary n. \\ n是完全合法的:\\字符将被替换为单个\\,然后您只有一个普通的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. 因此,您将获得一个包含反斜杠字符的字符串,然后是解析器传递的n个字符,而不是带有换行符的字符串。 The parser shouldn't have any problems with that. 解析器应该没有任何问题。

In your l4j2Logger.warn, you use two strings containing newline characters. 在l4j2Logger.warn中,使用两个包含换行符的字符串。 It seems that in the JSON document, "message" has a string value that represents the first argument. 在JSON文档中,“ message”似乎具有表示第一个参数的字符串值。 The "throwable" value seems has a string value that represents source code. “ throwable”值似乎具有一个表示源代码的字符串值。 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. 这似乎是有意的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM