gpt4 book ai didi

python - 记录处理程序 : How do I make sure I am not making two?

转载 作者:太空狗 更新时间:2023-10-30 01:35:19 24 4
gpt4 key购买 nike

编辑:我最终回答了我的问题,这样我就可以拥有一个可用的日志记录模块。但是,我还有一个相关的问题。请参阅下面我的回答。

我正在尝试通过始终记录到我所在的任何操作系统的临时目录来实现日志记录。为此,我编写了以下函数。

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”调用。

最佳答案

我最终回答了我自己的问题。这是代码

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 配置即使被多次调用也能正常工作。

如果有人知道如何检查日志对象上有哪些处理程序,我仍然想知道。这似乎是绝对不可能的。

关于python - 记录处理程序 : How do I make sure I am not making two?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5627219/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com