2011-04-11 69 views
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」調用。

回答

1

我最終回答了我自己的問題。這裏是代碼

global IS_SETUP 
IS_SETUP = False 
def setuplogger(filename = 'python.log', directory = None, format = 'L:%(name)s M:%(module)s T:%(asctime)s > %(levelname)s: %(message)s'): 
    global IS_SETUP 
    if directory == None: 
     fd, fname = tempfile.mkstemp() 
     directory = os.path.dirname(fname) 

    logging.basicConfig(filename = directory + '/' + filename, format = format) 
    IS_SETUP = True 

def getlog(logname, level = logging.INFO): 
    '''returns a logger with logname that will print to filename and directoryname.''' 
    if IS_SETUP == False: 
     setuplogger() 

    mylog = logging.getLogger(logname) 

    mylog.setLevel(level) 
    mylog.info('NEW LOGGER STARTED') 
    return mylog 

這可以避免雙重配置。而且,即使被稱爲多次,顯然基本配置也可以工作。

如果有人知道如何檢查日誌對象上的處理程序,我仍然想知道。這似乎絕對不可能。

+0

FWIW您可以訪問「mylog.handlers」來遍歷已安裝的處理程序列表 – amirpc 2012-07-10 19:15:06

相關問題