编辑:我最后回答了我的问题,以便我可以拥有一个正常工作的记录模块。但是,我还有一个相关的问题。请参阅下面的答案。
我试图通过始终记录到我所在的任何操作系统的临时目录来实现日志记录。为此,我编写了以下函数。
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”调用。
答案 0 :(得分: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
这避免了双重配置。此外,显然Basic配置即使被多次调用也会起作用。
如果有人知道如何检查日志对象上的处理程序,我仍然想知道。这似乎绝对不可能。