Python日志记录:禁用堆栈跟踪 [英] Python logging: disable stack trace

查看:145
本文介绍了Python日志记录:禁用堆栈跟踪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法可以在HandlerFormatter中禁用Python 3中的异常堆栈跟踪记录?

Is there a simple way to disable the logging of an exception stack trace in Python 3, either in a Handler or Formatter?

我需要另一个Handler中的堆栈跟踪,因此在对Logger的调用中设置exc_info=False不是一个选项.有没有比定义自己的Formatter更简单的方法?

I need the stack trace in another Handler, so setting exc_info=False, in the call to the Logger is not an option. Is there a simpler way than just defining my own Formatter?

推荐答案

禁用每个处理程序追溯输出的最简单选项是添加自定义

The easiest option to disable per handler traceback output is to add a custom logging.Filter subclass that alters the record object (rather than filter out records).

过滤器只需将记录上的exc_info设置为None:

The filter simply has to set exc_info on records to None:

class TracebackInfoFilter(logging.Filter):
    """Clear or restore the exception on log records"""
    def __init__(self, clear=True):
        self.clear = clear
    def filter(self, record):
        if self.clear:
            record._exc_info_hidden, record.exc_info = record.exc_info, None
            # clear the exception traceback text cache, if created.
            record.exc_text = None
        elif hasattr(record, "_exc_info_hidden"):
            record.exc_info = record._exc_info_hidden
            del record._exc_info_hidden
        return True

在您的处理程序上添加该过滤器 :

# do not display tracebacks in messages handled with this handler,
# by setting the traceback cache to a non-empty string:
handler_with_no_tracebacks.addFilter(TracebackInfoFilter())

但是,处理程序不会复制日志记录,并且传递相同日志记录以后的任何其他处理程序也将忽略格式追溯.因此,您还需要配置任何 other 处理程序以再次恢复信息:

However, handlers do not copy log records, and any other handler that is passed the same log record later on will also ignore formatting the traceback. So you also need to configure any other handlers to restore the information again:

for handler in logger.handlers:
    if not any(isinstance(f, TracebackInfoFilter) for f in handler.filters):
        handler.addFilter(TracebackInfoFilter(clear=False))

如果有人想在任何地方禁用所有追溯输出,那么向所有处理程序或记录器添加自定义过滤器可能会变得很乏味.在这种情况下,另一个选择是使用 功能;只需将记录的exc_info属性设置为None,无条件:

If anyone wanted to disable all traceback outputs, everywhere, then perhaps adding a custom filter to all handlers or loggers becomes tedious. In that case another option is to register a custom record factory with the logging.setLogRecordFactory() function; just set the exc_info attribute on records to None, unconditionally:

record_factory = logging.getLogRecordFactory()

def clear_exc_text(*args, **kwargs):
    record = record_factory(*args, **kwargs)
    record.exc_info = None
    return record

logging.setLogRecordFactory(clear_exc_text)

请注意,默认工厂只是 logging.LogRecord,但是上面的功能可以与任何已设置的自定义工厂一起使用.

Note that the default factory is just the logging.LogRecord class, but the above function does its best to work with any already-set custom factory.

当然,您也可以创建自己的Handler子类,其中

Of course, you can also create your own Handler subclass where the Handler.handle() sets and clears the exc_info attribute:

class NoTracebackHandler(logging.Handler):
    def handle(self, record):
        info, cache = record.exc_info, record.exc_text
        record.exc_info, record.exc_text = None, None
        try:
            super().handle(record)
        finally:
            record.exc_info = info
            record.exc_text = cache

这篇关于Python日志记录:禁用堆栈跟踪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆