我正在尝试使用Log4J(2.6.2)将日志存储在JSON文件中。我在JsonLayout
中使用了RollingFileAppender
,只要我不尝试附加到先前已经写入的文件中,它就可以正常工作。
这是我用于设置版式和Appender的代码:
Layout<?> layout = JsonLayout.createLayout(config, false, false, false, true, false, true, "[", "]", Charset.defaultCharset());
String appenderFileName = "mylogfile-latest.log.json";
String appenderFilePattern = "mylogfile-%i.log.json";
String appenderName = "MyAppender";
Appender appender = RollingFileAppender.createAppender(appenderFileName, appenderFilePattern, "true", appenderName, "true", "256", "true",
SizeBasedTriggeringPolicy.createPolicy(this.configuration.getLogMaxSize().toString()),
null, layout, null, "false", "false", null, config);
正如我所说的,这是我第一次在日志文件中编写代码时工作正常:
[
{
"timeMillis" : 1469620840442,
"thread" : "SimpleAsyncTaskExecutor-43",
"level" : "ERROR",
"loggerName" : "MyLogger",
"message" : "my log message",
"endOfBatch" : false,
"loggerFqcn" : "org.apache.logging.log4j.spi.AbstractLogger",
"threadId" : 243,
"threadPriority" : 5
}
, {
"timeMillis" : 1469620840442,
"thread" : "SimpleAsyncTaskExecutor-43",
"level" : "DEBUG",
"loggerName" : "MyLogger",
"message" : "my log message",
"endOfBatch" : false,
"loggerFqcn" : "org.apache.logging.log4j.spi.AbstractLogger",
"threadId" : 243,
"threadPriority" : 5
}
]
然后关闭我的附加程序,等等...并重新启动我的应用程序,当我将新日志写入此现有文件时,这就是我得到的:
[
{
"timeMillis" : 1469620840442,
"thread" : "SimpleAsyncTaskExecutor-43",
"level" : "ERROR",
"loggerName" : "MyLogger",
"message" : "my log message",
"endOfBatch" : false,
"loggerFqcn" : "org.apache.logging.log4j.spi.AbstractLogger",
"threadId" : 243,
"threadPriority" : 5
}
, {
"timeMillis" : 1469620840442,
"thread" : "SimpleAsyncTaskExecutor-43",
"level" : "DEBUG",
"loggerName" : "MyLogger",
"message" : "my log message",
"endOfBatch" : false,
"loggerFqcn" : "org.apache.logging.log4j.spi.AbstractLogger",
"threadId" : 243,
"threadPriority" : 5
}
]
{
"timeMillis" : 1469620840490,
"thread" : "SimpleAsyncTaskExecutor-43",
"level" : "ERROR",
"loggerName" : "MyLogger",
"message" : "my log message",
"endOfBatch" : false,
"loggerFqcn" : "org.apache.logging.log4j.spi.AbstractLogger",
"threadId" : 245,
"threadPriority" : 5
}
, {
"timeMillis" : 1469620840492,
"thread" : "SimpleAsyncTaskExecutor-43",
"level" : "DEBUG",
"loggerName" : "MyLogger",
"message" : "my log message",
"endOfBatch" : false,
"loggerFqcn" : "org.apache.logging.log4j.spi.AbstractLogger",
"threadId" : 245,
"threadPriority" : 5
}
]
由于Gson无法从该文件创建
List
,因此此问题使无法解析日志。您是否有关于如何解决此问题的想法,而又无需进行cr脚的黑客操作就删除多余的
]
并用逗号替换呢?谢谢!
最佳答案
JSONLayout执行此操作的原因是创建“格式正确的” JSON文档。您需要将每个文档放在其自己的文件中(带有开始和结尾方括号),这是正确的,这里不是这种情况。
您有两种选择:
对于JSONLayout,将complete = false设置为示例(在示例中为true),这将在不使用'['和']'的情况下将其打印出来。然后,您可以在调用GSON之前自己添加这些字符(因为该文件实际上不会具有数组)。
使用诸如org.json:json或GSON之类的简单内容创建自己的JSONLayout(您需要扩展AbstractStringLayout)以获取文件的字符串。