记录到 CSV 文件的正确方法是什么?

2024-04-23

我想以格式化的形式记录发送到繁忙的 http 服务器的每个请求的一些信息。使用logging模块会创建一些我不想要的东西:

[I 131104 15:31:29 Sys:34]

我想到了CSV格式,但不知道如何定制。 Python 有csv模块,但我在手册中读到

import csv
with open('some.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerows(someiterable)

由于它每次都会打开和关闭一个文件,恐怕这种方式会降低整个服务器的性能。我能做什么?


只需使用Python的logging http://docs.python.org/2/library/logging.html module.

您可以按照您想要的方式调整输出;看一眼更改显示消息的格式 http://docs.python.org/2/howto/logging.html#changing-the-format-of-displayed-messages:

要更改用于显示消息的格式,您需要指定要使用的格式:

import logging
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
logging.debug('This message should appear on the console')
logging.info('So should this')
logging.warning('And this, too')

and 格式化程序 http://docs.python.org/2/howto/logging.html#formatters:

格式化程序对象配置日志消息的最终顺序、结构和内容。

您将在此处找到可以使用的属性列表:日志记录属性 http://docs.python.org/2/library/logging.html#logrecord-attributes.


如果你想生成一个有效的 csv 文件,请使用 python 的csv module https://docs.python.org/3/library/csv.html, too.

这是一个简单的例子:

import logging
import csv
import io

class CsvFormatter(logging.Formatter):
    def __init__(self):
        super().__init__()
        self.output = io.StringIO()
        self.writer = csv.writer(self.output, quoting=csv.QUOTE_ALL)

    def format(self, record):
        self.writer.writerow([record.levelname, record.msg])
        data = self.output.getvalue()
        self.output.truncate(0)
        self.output.seek(0)
        return data.strip()

logging.basicConfig(level=logging.DEBUG)

logger = logging.getLogger(__name__)
logging.root.handlers[0].setFormatter(CsvFormatter())

logger.debug('This message should appear on the console')
logger.info('So should "this", and it\'s using quoting...')
logger.warning('And this, too')

Output:

“DEBUG”,“此消息应出现在控制台上”
“INFO”,“““this””也应该如此,并且它使用引用......”
“警告”,“还有这个”

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

记录到 CSV 文件的正确方法是什么? 的相关文章

随机推荐