Python 如何更改与logging.captureWarnings()关联的记录器?
在我的应用程序中,我使用来确保任何日志都记录在正常的应用程序日志中 这很好,但会产生如下日志:Python 如何更改与logging.captureWarnings()关联的记录器?,python,logging,deprecation-warning,Python,Logging,Deprecation Warning,在我的应用程序中,我使用来确保任何日志都记录在正常的应用程序日志中 这很好,但会产生如下日志: WARNING [py.warnings] c:\some\path... 似乎: 如果捕获为True,则警告模块发出的警告将被删除 已重定向到日志记录系统。具体而言,将发出警告 使用warnings.formatwarning()和结果字符串格式化 登录到名为“py.warnings”的记录器,严重程度为警告 所以这就是我们所期待的。但是我想更改与此类警告相关联的日志记录程序(使用我的应用程序提供
WARNING [py.warnings] c:\some\path...
似乎:
如果捕获为True,则警告模块发出的警告将被删除
已重定向到日志记录系统。具体而言,将发出警告
使用warnings.formatwarning()和结果字符串格式化
登录到名为“py.warnings”的记录器,严重程度为警告
所以这就是我们所期待的。但是我想更改与此类警告相关联的日志记录程序(使用我的应用程序提供的日志记录程序,以便在查看日志时知道DeprecationWarning
的来源)
有没有办法更改相关的记录器?我只是做了一些进一步的调查,找到了一个完美的方法来实现这一点: 查看
日志记录的源代码。captureWarnings()
:
似乎可以更改warnings.showwarnings
以指向另一个可调用项,该可调用项将执行您想要的任何日志记录工作(或任何其他相关工作)
warning.showwarning
的预期原型似乎是:
def _show_warning(message, category, filename, lineno, file=None, line=None):
"""Hook to write a warning to a file; replace if you like."""
if file is None:
file = sys.stderr
try:
file.write(formatwarning(message, category, filename, lineno, line))
except IOError:
pass # the file (probably stderr) is invalid - this warning gets lost.
似乎logging.captureWarnings()
实际上将调用设置为logging.\u showwarning
:
def _showwarning(message, category, filename, lineno, file=None, line=None):
"""
Implementation of showwarnings which redirects to logging, which will first
check to see if the file parameter is None. If a file is specified, it will
delegate to the original warnings implementation of showwarning. Otherwise,
it will call warnings.formatwarning and will log the resulting string to a
warnings logger named "py.warnings" with level logging.WARNING.
"""
if file is not None:
if _warnings_showwarning is not None:
_warnings_showwarning(message, category, filename, lineno, file, line)
else:
s = warnings.formatwarning(message, category, filename, lineno, line)
logger = getLogger("py.warnings")
if not logger.handlers:
logger.addHandler(NullHandler())
logger.warning("%s", s)
def _showwarning(message, category, filename, lineno, file=None, line=None):
"""
Implementation of showwarnings which redirects to logging, which will first
check to see if the file parameter is None. If a file is specified, it will
delegate to the original warnings implementation of showwarning. Otherwise,
it will call warnings.formatwarning and will log the resulting string to a
warnings logger named "py.warnings" with level logging.WARNING.
"""
if file is not None:
if _warnings_showwarning is not None:
_warnings_showwarning(message, category, filename, lineno, file, line)
else:
s = warnings.formatwarning(message, category, filename, lineno, line)
logger = getLogger("py.warnings")
if not logger.handlers:
logger.addHandler(NullHandler())
logger.warning("%s", s)