5
編輯:我結束了回答我的問題的牛肉,以便我可以有一個工作日誌模塊。不過,我仍然有一個相關的問題。請參閱下面的答案。記錄處理程序:我如何確保我不做兩個?
我試圖通過始終記錄到任何我所在的操作系統的臨時目錄來實現日誌記錄。爲此,我編寫了以下函數。
import logging, tempfile, os, sys
def getlog(logname, filename = 'python.log', directory = None):
'''returns a logger with logname that will print to filename and directoryname.'''
if directory == None:
fd, fname = tempfile.mkstemp()
directory = os.path.dirname(fname)
fullpath = directory + '/' + filename
mylog = logging.getLogger(logname)
hdlr = logging.FileHandler(fullpath)
formatter = logging.Formatter('L:%(name)s M:%(module)s T:%(asctime)s > %(levelname)s: %(message)s')
hdlr.setFormatter(formatter)
mylog.addHandler(hdlr)
mylog.setLevel(logging.INFO)
mylog.info('NEW LOGGER STARTED')
return mylog
if __name__ == '__main__':
log = getlog('testing')
log.info('working?')
log.info('yes, seems to be working')
log2 = getlog('testing')
log2.info('still working?')
這裏是輸出:
L:testing M:easy_log T:2011-04-11 15:30:14,315 > INFO: NEW LOGGER STARTED
L:testing M:easy_log T:2011-04-11 15:30:14,316 > INFO: working?
L:testing M:easy_log T:2011-04-11 15:30:14,316 > INFO: yes, seems to be working
L:testing M:easy_log T:2011-04-11 15:30:14,316 > INFO: NEW LOGGER STARTED
L:testing M:easy_log T:2011-04-11 15:30:14,316 > INFO: NEW LOGGER STARTED
L:testing M:easy_log T:2011-04-11 15:30:14,316 > INFO: still working?
L:testing M:easy_log T:2011-04-11 15:30:14,316 > INFO: still working?
正如你可以看到,現在是雙輸出。但是,日誌記錄模塊相當混亂,我不知道如何查看日誌是否已被實例化,或者日誌對象是否具有處理程序。一些幫助將不勝感激。
編輯:爲了增加一點細節,我打算在幾個模塊中調用它,本質上是試圖替換「logging.getLogger」調用。
FWIW您可以訪問「mylog.handlers」來遍歷已安裝的處理程序列表 – amirpc 2012-07-10 19:15:06