2013-11-04 32 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)

相關問題