请考虑以下代码:
import logging
print "print"
logging.error("log")
我得到:
print
ERROR:root:log
现在,如果我在前一段代码的开头包含一个thid party模块并重新运行它,我只得到:
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")
一个更完整的解决方案,不会使任何伐木工人失效。应该可以工作,除非某个模块执行了一些奇怪的操作,比如保存对筛选器或处理程序的引用。
不用说,您必须在运行
reset_logging()
之后设置日志记录。要从根日志记录器中完全清除现有日志配置,这可能有效:
但是,这不会重置为“默认”,这会清除所有内容。然后你必须添加一个
StreamHandler
来实现你想要的。这取决于另一个模块在做什么;例如,如果它正在调用
logging.disable
,那么您可以调用logging.disable(logging.NOTSET)
来重置它。您可以尝试重新加载
logging
模块:问题是这将使第三方模块及其自己的
logging
副本处于不可用状态,因此以后可能会导致更多问题。相关问题 更多 >
编程相关推荐