Py学习  »  Python

python:logging.warn()添加stacktrace

guettli • 7 年前 • 1687 次点击  

有几个 logging.warn('....') 调用我今天正在处理的旧代码库。

我想更好地理解日志输出。到现在为止 logging.warn() 确实发出一行。但这条单行线不足以理解上下文。

我想看看解释器的stacktrace。

因为有很多 日志记录。警告(“…”) 代码中的行,我希望它们保持原样,并且只修改 配置 日志记录。

如何将解释程序stacktrace添加到 warn() 或 error() 自动呼叫?

我知道。 logging.exception("message") 显示stacktrace,但我想离开 日志记录。警告() 线条未动。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38695
文章 [ 2 ]  |  最新文章 7 年前
Bharel
Reply   •   1 楼
Bharel    8 年前

我不相信一个管理者是你的解决方案。选择过滤器:

import os.path
import traceback
import logging
_LOGGING_FILE = os.path.normcase(logging.addLevelName.__code__.co_filename)
_CURRENT_FILE = os.path.normcase(__file__)
_ELIMINATE_STACK = (_CURRENT_FILE, _LOGGING_FILE)


class AddStackFilter(logging.Filter):
    def __init__(self, levels=None):
        self.levels = levels or set()

    def get_stack(self):
        # Iterator over file names
        filenames = iter(_ELIMINATE_STACK)
        filename = next(filenames, "")
        frames = traceback.walk_stack(None)

        # Walk up the frames
        for frame, lineno in frames:

            # If frame is not from file, continue on to the next file
            while os.path.normcase(frame.f_code.co_filename) != filename:
                filename = next(filenames, None)
                if filename is None:
                    break
            else:
                # It's from the given file, go up a frame
                continue

            # Finished iterating over all files
            break

        # No frames left
        else:
            return None

        info = traceback.format_stack(frame)
        info.insert(0, 'Stack (most recent call last):\n')

        # Remove last newline
        info[-1] = info[-1].rstrip()

        return "".join(info)

    def filter(self, record):
        if record.levelno in self.levels:
            sinfo = self.get_stack()
            if sinfo is not None:
                record.stack_info = sinfo

        return True

此过滤器有许多优点:

  1. 从本地文件和日志记录文件中删除堆栈帧。
  2. 留下堆栈帧,以防在通过日志记录后返回到本地文件。重要的是,如果我们希望将同一个模块用于其他内容。
  3. 您可以将它附加到任何处理程序或记录器,而不会将您绑定到streamhandler或任何其他处理程序。
  4. 您可以使用相同的筛选器或单个处理程序影响多个处理程序。
  5. 等级表示为 __init__ 变量,允许您根据需要添加更多级别。
  6. 允许您将堆栈跟踪添加到日志中,而不仅仅是打印。
  7. 很好地处理日志模块,将堆栈放在正确的位置,没有什么意外。

用途:

>>> import stackfilter
>>> import logging
>>> sfilter = stackfilter.AddStackFilter(levels={logging.WARNING})
>>> logging.basicConfig()
>>> logging.getLogger().addFilter(sfilter)
>>> def testy():
...     logging.warning("asdasd")
...
>>> testy()
WARNING:root:asdasd
Stack (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in testy
georgexsh
Reply   •   2 楼
georgexsh    8 年前

如果您接受添加日志处理程序,这很简单:

import logging
import traceback


class WarnWithStackHandler(logging.StreamHandler):
    def emit(self, record):
        if record.levelno == logging.WARNING:
            stack = traceback.extract_stack()
            # skip logging internal stacks
            stack = stack[:-7]
            for line in traceback.format_list(stack):
                print(line, end='')
        super().emit(record)