写入基于 XML 的大型日志文件时性能不佳

Poor performance when writing large XML-based log file

我对 Python 比较陌生,我已经为定义的应用程序列表编写了一个相当简单的脚本记录性能统计信息。该脚本以一定间隔(使用 psutil)和 returns 对各种统计数据进行采样,然后将其记录下来。为了以后更容易对数据做有趣的事情,我使用了 XML 日志格式。

下面是日志结构的简化版:

<?xml version="1.0" ?>
<data>
    <periodic>
        <sample name="2015-02-25_23-22-54">
            <cpu app="safari">10.5</cpu>
            <memory app="safari">1024</memory>
            <disk app="safari">60</disk>
            <network app="safari">720</network>
        </sample>
    </periodic>
</data>

我目前正在使用 cElementTree 来解析和创建日志文件。采样循环的每次迭代都会解析现有日志文件,将最新数据附加到末尾,然后将新文件写入磁盘。

我的日志编写器的简化版class:

import xml.etree.cElementTree as etree
from xml.dom import minidom

logfile = 'path/to/logfile.xml'

class WriteXmlLog:
    # Parse the logfile.
    def __init__(self):
        self.root = etree.parse(logfile).getroot()
        self.periodic = list(self.root.iter('periodic'))[0]

    def __write_out(self, log_file):
        """Write log contents to file."""
        open(log_file, 'w').write(minidom.parseString(etree.tostring(self.root).replace('\n', '').replace('\t', '')).toprettyxml())

    def __create_timestamp(self):
        """Returns a timestamp for naming a process sample iteration."""
        return datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d_%H-%M-%S')

    def write_sample(self, sample_list):
        """Create or append sample to XML log file."""
        node_sample_time = etree.Element('sample')
        node_sample_time.set('time', self.__create_timestamp())
        for i in sample_list:
            app_dict = i.get('values')
            for a in app_dict:
                sample = etree.Element(a)
                app = str(i.get('appname')).lower()
                sample.set('app', app)
                sample.text = app_dict[a]
                node_sample_time.append(sample)
        self.periodic.append(node_sample_time)
        self.__write_out(logfile)

我遇到的问题是,虽然这个脚本在日志文件很小的情况下工作得很好,但它被用于我们必须每隔几秒对相同进程进行采样的情况,有时甚至几天运行.这可以生成最大 10 MB 的日志文件(此时它们会轮换)。 运行 这个大小的日志上的脚本大约需要 15 秒,并且在整个持续时间内挂上 1 CPU 个核心,更不用说过多的内存使用和磁盘 I/O.

__write_out() 可能不是很有效,因为它运行两个搜索和替换操作(去除无关的换行符和制表符,弄乱 toprettyxml),然后在每次迭代时通过 minidom 发送整个输出.这样做是因为 cElementTree 不会自行缩进节点,从而使生成的文件难以阅读。然而,真正的问题似乎只是每次迭代解析和写入整个日志本质上是不可扩展的。

我的第一个想法是完全放弃使用 cElementTree,"manually" 将结果格式化为 XML 字符串,然后在每次迭代时将它们附加到日志文件的末尾(根本不解析现有文件)。这种方法的问题是生成的文件将无效 XML 因为根节点没有结束标记。我可以让记录器在完成时写一个(它目前设计为无限循环直到 SIGTERM,然后在退出时做一些清理)但我希望日志文件在记录期间始终有效 XML .它在某种程度上也显得笨拙。

总结:写入基于 XML 的日志文件的最佳方法是什么,该文件具有良好的性能和合理的资源使用率,可以扩展到日志文件大小大约 10 MB?

如果我没理解错的话,您可以创建每个 "periodic" 元素,就好像它是一个完整的文档一样(因此您仍然可以使用 cElementTree 或类似工具;或者只是将其手动创建为字符串)。

然后当需要写出这样一个(小)元素时,打开您的日志文件,并查找到减去“”(7) 长度的末尾。写入新的周期元素,然后重新写入“”,应该就可以了。

如果您想格外小心,移动到末尾后,请阅读最后 7 个字符以确保它们符合预期,然后再次搜索以再次将文件定位在它们之前。