gpt4 book ai didi

python - 导入对日志记录的副作用 : how to reset the logging module?

转载 作者:太空狗 更新时间:2023-10-29 17:59:41 26 4
gpt4 key购买 nike

考虑这段代码:

import logging
print "print"
logging.error("log")

我得到:

print
ERROR:root:log

现在,如果我在之前代码的开头包含一个第三方模块并重新运行它,我只会得到:

print

之前有一些关于此的问题,但在这里我无法触摸我正在导入的模块。

第三方模块的代码在这里:http://atlas-sw.cern.ch/cgi-bin/viewcvs-atlas.cgi/offline/DataManagement/DQ2/dq2.clientapi/lib/dq2/clientapi/DQ2.py?view=markup ,但我的问题更笼统:独立于我正在导入的模块,我想要一个干净的 logging 以预期的方式工作

一些(非工作)建议的解决方案:

from dq2.clientapi.DQ2 import DQ2
import logging
del logging.root.handlers[:]

from dq2.clientapi.DQ2 import DQ2
import logging
logging.disable(logging.NOTSET)

logs = logging.getLogger('root')
logs.error("Some error")

下一个有效,但产生了一些额外的错误:

from dq2.clientapi.DQ2 import DQ2
import logging
reload(logging)

我得到:

print
ERROR:root:log
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
File "/afs/cern.ch/sw/lcg/external/Python/2.6.5/x86_64-slc5-gcc43- opt/lib/python2.6/atexit.py", line 24, in _run_exitfuncs
func(*targs, **kargs)
File "/afs/cern.ch/sw/lcg/external/Python/2.6.5/x86_64-slc5-gcc43-opt/lib/python2.6/logging/__init__.py", line 1509, in shutdown
h.close()
File "/afs/cern.ch/sw/lcg/external/Python/2.6.5/x86_64-slc5-gcc43-opt/lib/python2.6/logging/__init__.py", line 705, in close
del _handlers[self]
KeyError: <logging.StreamHandler instance at 0x2aea031f7248>
Error in sys.exitfunc:
Traceback (most recent call last):
File "/afs/cern.ch/sw/lcg/external/Python/2.6.5/x86_64-slc5-gcc43-opt/lib/python2.6/atexit.py", line 24, in _run_exitfuncs
func(*targs, **kargs)
File "/afs/cern.ch/sw/lcg/external/Python/2.6.5/x86_64-slc5-gcc43-opt/lib/python2.6/logging/__init__.py", line 1509, in shutdown
h.close()
File "/afs/cern.ch/sw/lcg/external/Python/2.6.5/x86_64-slc5-gcc43-opt/lib/python2.6/logging/__init__.py", line 705, in close
del _handlers[self]
KeyError: <logging.StreamHandler instance at 0x2aea031f7248>

from dq2.clientapi.DQ2 import DQ2
import logging
logger = logging.getLogger(__name__)
ch = logging.StreamHandler()
logger.addHandler(ch)
logger.error("log")

最佳答案

这取决于其他模块在做什么;例如如果它正在调用 logging.disable 那么您可以调用 logging.disable(logging.NOTSET) 来重置它。

您可以尝试重新加载logging 模块:

from importlib import reload
logging.shutdown()
reload(logging)

问题是这将使第三方模块及其自己的 logging 副本处于无法使用的状态,因此以后可能会导致更多问题。

关于python - 导入对日志记录的副作用 : how to reset the logging module?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12034393/

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