跳转到主要内容

自动记录异常:将日志消息附加到异常并在条件满足时输出。

项目描述

安装

使用setup.py

python setup.py install

警告

此模块在导入时会修改sys.excepthook

用法

自动记录异常

将日志消息附加到异常

import logging
import logging_exceptions as exlog

e = ValueError("Wrong value")
logger = logging.getLogger(__name__)
with exlog.log_to_exception(logger, e):
    logger.critical("This is a %s log mressage", "long")
raise e # The exception can also be raised inside the with statement

如果没有捕获错误,则在程序终止时显示日志消息。

捕获错误并在自定义日志级别下显示日志消息

import logging_exceptions as exlog
import logging
try:
    e = ValueError("Wrong value")
    logger = logging.getLogger(__name__)
    with exlog.log_to_exception(logger, e):
        logger.critical("This is a %s log mressage", "long")
        raise e
except ValueError as err:
    exlog.log(err, level=logging.DEBUG, with_stacktrace=False)

在这里,exlog.logexlog.log_exception的同义词

从不同的函数名和行号进行日志记录

log_exception中的代码调用Logger对象的_log函数。为了避免记录log_to_exception的函数名和行号,logging_exception调用logging.setLoggerClass(ExlogLogger)将导入logging_exception后创建的所有日志记录器的类设置为ExlogLogger。

ExlogLogger是本模块定义的logging.Logger的子类。它覆盖了findCaller以更多地控制记录的调用者。除了忽略logging_exceptions中定义的函数外,ExlogLogger类还有公开属性ignored_functions。

通过将函数名添加到ignored_functions中,可以记录匹配函数的父函数而不是匹配函数作为调用者。

特别是,可以在辅助函数中使用上下文管理器logging_exceptions.log_at_caller来临时更新记录器的ignored_functions,以便记录函数的调用者而不是函数。

以下代码将生成一个函数名为foo的日志消息,而不是helper_function

import logging_exceptions as exlog
logger = logging.get_logger(__name__)
def helper_function():
   with exlog.log_at_caller(logger):
     logger.log("This is a log message")
def foo():
   helper_function()

命令行便利函数

以下便捷函数与异常处理无直接关联,但如果你使用argparse,它们会很有用。

将‘–verbose’、‘–debug’和‘–quiet’选项添加到argparse.Argumentparser实例中。

import argparse
import logging_exceptions as exlog

parser=argparse.ArgumentParser("Some help text")
exlog.update_parser(parser)
args = parser.parse_args()

logging.basicConfig()
# The following call updates the log levels of the root logger
# and potential some other loggers.
exlog.config_from_args(args)

现在可以通过以下方式从命令行使用脚本

# Set the log-level for the loggers with the names `path.to.module1`
# and `path.to.module2` to DEBUG.
python script.py --debug path.to.module1,path.to.module2

示例

请参阅文件‘logging_exceptions_examples.py’

与logging.handlers.MemoryHandler的比较

logging.handlers模块包含一个类似用途的处理程序:MemoryHandler。它缓冲日志消息,只有在遇到严重性为ERROR或更严重的日志记录时才发出。我将简要解释MemoryHandler和我的模块之间的区别

如果你知道将来可能会发生严重性为ERROR的事件(通常在同一函数中),并且你想为此潜在异常做准备,MemoryHandler就非常出色。通常,你知道需要缓冲异常的作用域,也知道何时不再需要缓冲的异常并可以丢弃。

而对于MemoryHandler来说,错误条件相对不具体,而我们必须决定是否丢弃和发出日志消息的作用域是明确的。

另一方面,log_to_exception装饰器在异常明确指定(已创建/捕获)但可能被捕获或未被捕获的作用域不明确时很有用。例如,可以抛出错误的库函数。

一个典型的例子如下

import logging
from logging_exceptions import log_to_exception

# Whoever calls public_function may want to catch the ValueError and hide
# the log messages or change their level to logging.DEBUG
def public_function():
    logger = logging.getLogger(__name__)
    a = some_complex_calculation(12)
    try:
        some_function(a)
    except ValueError as e:
        with log_to_exception(logger, e):
            log.error("While calling `some_function` with %s, "
                      "which is result of `some_complex_calculation`(%d),"
                      " an error occurred", a, 12)
        raise

兼容性

兼容Python 2.7和Python 3

项目详情


下载文件

下载适用于您的平台文件。如果您不确定选择哪个,请了解有关安装包的更多信息。

源分发

logging_exceptions-0.1.9.tar.gz (7.6 kB 查看哈希值)

上传时间

支持者

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面