2013-11-04 33 views
7

我想记录每一个请求的一些信息发送给繁忙的http服务器以格式化形式,使用日志模块会创建一些事情,我不想:什么是在csv文件中进行日志记录的正确方法?

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

我认为csv格式的,但我不知道如何来定制它,蟒蛇了CSV模块,但阅读手册

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

,因为它会打开,每次关闭文件,恐怕以这种方式将整个服务器慢下来表演,我该怎么办?

+1

您应该使用logging.Formatter实例与输出CSV行的格式。 –

回答

6

只需使用python的logging模块。

您可以根据需要调整输出;看看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')

Formatters

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

您可以用,轻松替换:以创建一个类似CSV的输出文件。

您可以在此处使用attribtus列表:LogRecord attributes

0

我不认为这是最好的主意,但它是可行的,而且很简单。 手动缓冲你的日志。将日志条目存储在某个地方,并不时写入文件。 如果您知道您的服务器将经常繁忙,请在缓冲区达到一定尺寸时清空它。如果在使用上可能存在很大差距,我会说,新的线程(或更好的过程,检查自己为什么线程吸入和放慢应用程序)与无休止的(理论上当然)睡眠/冲洗循环会更好的呼叫。 另外,请记住创建某种钩子,当服务器中断或失败时可以刷新缓冲区(可能是信号?或者只是尝试/主函数除外 - 还有更多方法可以做到这一点),所以你不会失去清理缓冲数据意外退出。

我再说一遍 - 这不是最好的主意,这是我想起来的第一件事。您可能需要咨询Flask或其他webapp框架的日志实现(AFAIR Flask也有CSV日志记录)。

1

正如懒惰建议的那样,您可以轻松地将日志的分隔符编辑为逗号,从而生成一个CSV文件。

工作例如:

import logging 

# create logger 
lgr = logging.getLogger('logger name') 
lgr.setLevel(logging.DEBUG) # log all escalated at and above DEBUG 
# add a file handler 
fh = logging.FileHandler('path_of_your_log.csv') 
fh.setLevel(logging.DEBUG) # ensure all messages are logged to file 

# create a formatter and set the formatter for the handler. 
frmt = logging.Formatter('%(asctime)s,%(name)s,%(levelname)s,%(message)s') 
fh.setFormatter(frmt) 

# add the Handler to the logger 
lgr.addHandler(fh) 

# You can now start issuing logging statements in your code 
lgr.debug('a debug message') 
lgr.info('an info message') 
lgr.warn('A Checkout this warning.') 
lgr.error('An error writen here.') 
lgr.critical('Something very critical happened.') 
+2

是有办法增加一个CSV标题行? (?即,在包含列名称的CSV文本文件中的第一行) – ycomp

+0

唉,这可能是你在找什么:http://stackoverflow.com/questions/27840094/write-a-header-at -every-日志文件 - 即-是创建与 - 一个时间旋转记录器 – ecoe

2

我同意你应该使用日志模块,但你真的不能做正确只是一个格式字符串像一些其他的答案显示,因为他们做的不能解决记录包含逗号的消息的情况。

如果你需要一个解决方案,将正确转义消息中的任何特殊字符(或其他领域,我想),你会写一个自定义的格式进行设置。

logger = logging.getLogger() 

formatter = MyCsvFormatter() 

handler = logging.FileHandler(filename, "w") 
handler.setFormatter(formatter) 
logger.addHandler(handler) 
logger.setLevel(level) 

你显然必须实现MyCsvFormatter类,它应该从logging.Formatter继承和覆盖format()方法

class MyCsvFormatter(logging.Formatter): 
    def __init__(self): 
     fmt = "%(levelname)s,%(message)s" # Set a format that uses commas, like the other answers 
     super(MyCsvFormatter, self).__init__(fmt=fmt) 

    def format(self, record): 
     msg = record.getMessage() 
     # convert msg to a csv compatible string using your method of choice 
     record.msg = msg 
     return super(MyCsvFormatter, self).format(self, record) 

注:我以前做过这样的事情,但还没有测试过这个特殊的代码示例

至于做信息的实际逃逸,这里有一个可能的方法: Python - write data into csv format as string (not file)

相关问题