繁体   English   中英

例外:仅记录一次回溯

[英]Exceptions: logging the traceback only once

我正在摸索什么是仅在日志文件中获取一次回溯的最佳实践。 请注意,通常我知道如何将回溯记录到日志中。

假设我有一个由各种模块和导入的函数组成的大程序,因此它可以具有相当的深度并且记录器设置正确。

每当可能发生异常时,我都会执行以下操作:

try:
    do_something()
except MyError as err:
    log.error("The error MyError occurred", exc_info=err)
    raise

请注意,回溯是通过选项exc_info=err写入日志的。

我现在的问题是,当一切都变得更加复杂和嵌套时,我失去了对该回溯写入日志的频率的控制,并且变得非常混乱。

我目前针对此问题的解决方案的情况示例如下:

from other_module import other_f

def main():

    try:
        # do something
        val = other_f()

    except (AlreadyLoggedError1, AlreadyLoggedError2, AlreadyLoggedError3):
        # The error was caught within other_f() or deeper and 
        # already logged with traceback info where it occurred
        # After logging it was raised like in the above example
        # I do not want to log it again, so it is just raised
        raise
    except BroaderException as err:
        # I cannot expect to have thought of all exceptions
        # So in case something unexpected happened 
        # I want to have the traceback logged here
        # since the error is not logged yet
        log.error("An unecpected error occured", exc_info=err)
        raise

这个解决方案的问题是,我需要跟踪我自己已经记录的所有异常,并且except (AlreadyLoggedError1, AlreadyLoggedError2, ...)的行变得任意长并且必须放在 main( ) 和 position 实际发生的错误。

所以我的问题是:有没有更好的(pythonic)方法来处理这个? 更具体地说:我想提出异常已经与异常一起记录的信息,这样我就不必像上面的示例中那样通过额外的 except 块来解释这一点。

通常用于大型应用程序的解决方案是,如果只是要记录低级代码,则实际上不会自己进行错误处理,而是将异常记录/处理放在代码中的最高级别,因为异常会冒泡根据需要。 例如,向 New Relic 和 Sentry 等服务发送错误的库不需要您检测代码中可能引发错误的每一小部分,它们被设置为捕获任何异常并将其发送到远程服务用于聚合和跟踪。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM