1

私のアプリケーションでは、通常のアプリケーション ログに記録されるlogging.captureWarnings(True)ことを確認するために使用しています。DeprecationWarning

これはうまく機能しますが、次のようなログが生成されます。

WARNING [py.warnings] c:\some\path...

ドキュメントから次のように思われます。

キャプチャが True の場合、警告モジュールによって発行された警告はログ システムにリダイレクトされます。具体的には、警告は warnings.formatwarning() を使用してフォーマットされ、結果の文字列は重大度 WARNING で「py.warnings」という名前のロガーに記録されます。

期待されるのはそれだけです。しかし、そのような警告に関連付けられているロガーを変更したいと思います(アプリケーションが提供するものを使用して、ログを見てどこからDeprecationWarning来たかを知ることができます)。

関連するロガーを変更する方法はありますか?

4

1 に答える 1

2

さらに調査を行ったところ、それを達成するための完璧な方法が見つかりました。

のソースコードを見るlogging.captureWarnings()

def captureWarnings(capture):
    """
    If capture is true, redirect all warnings to the logging package.
    If capture is False, ensure that warnings are not redirected to logging
    but to their original destinations.
    """
    global _warnings_showwarning
    if capture:
        if _warnings_showwarning is None:
            _warnings_showwarning = warnings.showwarning
            warnings.showwarning = _showwarning
    else:
        if _warnings_showwarning is not None:
            warnings.showwarning = _warnings_showwarning
            _warnings_showwarning = None

warnings.showwarning必要なロギングジョブ(またはその他のこと)を実行する別の呼び出し可能オブジェクトを指すように変更できるようです。

の予想されるプロトタイプは次のwarnings.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()実際には callable を次のように設定しているようですlogging._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)
于 2015-02-06T14:28:59.463 に答える