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