在csv文件中进行登录的正确方法是什么? [英] what is the proper way to do logging in csv file?
问题描述
我想以格式的形式记录发送到繁忙的http服务器的每个请求的一些信息,使用日志模块会创建一些我不想记录的东西:
i want to log some information of every single request send to a busy http server in a formatted form,use log module would create some thing i don't want to:
[I 131104 15:31:29 Sys:34]
我想到的是csv格式,但是我不知道如何自定义它,而python有了csv模块,但是请阅读手册
i think of csv format but i don't know how to customize it,and python got csv module,but read the manual
import csv
with open('some.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(someiterable)
由于每次都会打开和关闭文件,因此恐怕以此方式会降低整个服务器的性能,我该怎么办?
since it would open and close a file each time, i am afraid in this way would slow down the whole server performance, what could i do?
推荐答案
只需使用python的> c0> 模块.
Just use python's logging
module.
您可以根据需要调整输出;看看更改显示格式消息:
You can adjust the output the way you want; take a look at Changing the format of displayed messages:
要更改用于显示消息的格式,您需要指定要使用的格式:
To change the format which is used to display messages, you need to specify the format you want to use:
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')
和格式化程序:
格式化程序对象配置日志消息的最终顺序,结构和内容.
Formatter objects configure the final order, structure, and contents of the log message.
您将在此处找到可以使用的属性列表: LogRecord属性.
You'll find a list of the attribtus you can use here: LogRecord attributes.
如果要生成有效的csv文件,请使用python的 csv
模块.
If you want to produce a valid csv-file, use python's csv
module, 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')
输出:
"DEBUG",此消息应出现在控制台上"
"INFO"," this也应如此,并且使用引号..."
警告",这也是"
"DEBUG","This message should appear on the console"
"INFO","So should ""this"", and it's using quoting..."
"WARNING","And this, too"
这篇关于在csv文件中进行登录的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!