问题描述
日志文件不是要由机器读取,而是用户?我想知道是否有任何记录框架的文件附录将其输出写入XML.
推荐答案
"登录到XML"是一个一般要求,因为没有标准日志文件格式之类的内容.但是,由于XML文件是文本文件,记录框架可以编写,并且由于许多框架允许配置日志线格式,因此我认为使用选择的XML标签定义日志输出时没有问题.
对于log4j,可能是这样的:
log4j.appender.A1.layout.ConversionPattern=<line>%n<date>%d</date>%n<threadName>%t</threadName>%n<level>%p</level>%n<logger>%c</logger>%n<text>%m</text>%n</line>%n
产生示例输出:
<line> <date>2011-08-28 08:27:33,727</date> <threadName>main</threadName> <level>INFO</level> <logger>com.log4jeval.Main</logger> <text>Entering application.</text> </line>
这看起来很像XML,不是吗?但是,它将缺乏XML序言,因此从技术上讲,它是无效的.如果至关重要,我建议编写一个自定义的appender扩展org.apache.log4j.FileAppender(或其任何子类),该org.apache.log4j.FileAppender将处理每个日志文件中的任何其他打开/关闭文本.
将日志写入XML的问题(在纯文本文件中都不存在),您必须强制执行不是一个可能的日志语句会打印XML禁止字符,否则您将结束用非格式的XML升高.在不编写自定义的附录器的情况下,这很难实现 - 例如,请参见org.apache.log4j.HTMLAppender来源.
问题描述
Are log files not meant to be read by machines but by users only? I wonder if there are file appenders for any logging framework that write their output to XML.
推荐答案
"Logging to XML" is quite a general requirement, because there is no such thing as the standard log file format. But since XML files are text files, which logging frameworks can write, and since many of those frameworks allow configuring log line format, I see no problem in defining your log output with XML tags of choice.
For log4j, it might be something like this:
log4j.appender.A1.layout.ConversionPattern=<line>%n<date>%d</date>%n<threadName>%t</threadName>%n<level>%p</level>%n<logger>%c</logger>%n<text>%m</text>%n</line>%n
yielding example output:
<line> <date>2011-08-28 08:27:33,727</date> <threadName>main</threadName> <level>INFO</level> <logger>com.log4jeval.Main</logger> <text>Entering application.</text> </line>
This looks quite like XML, doesn't it? It will lack XML preamble, though, so technically it won't be valid. If it's critical that it is, I recommend writing a custom appender extending org.apache.log4j.FileAppender (or any of its subclasses) that would handle any additional opening/closing text in every log file.
The problem with writing logs to XML, that does not exist in plain text files, is that you have to enforce that not one possible log statement would print XML forbidden characters, otherwise you'll end up with a non well-formed XML. That's hard to achieve without writing a custom appender — see org.apache.log4j.HTMLAppender sources for example.