首页 > 解决方案 > python:在哪里记录异常

问题描述

我正在寻找一些“最佳实践”的建议。

在我的 Python 应用程序中,我使用异常来控制程序的流程。但我不确定应该在哪里记录异常。我的直觉说我应该将它记录在最接近引发异常的位置。但这会导致一些相当笨重的代码:

def a_deeper_level_function():
    print("I am doing stuff, but it goes wrong. So raising.")
    
    # but I also want to log here with the same message.
    # so I put my msg in a separate variable to re-use it.

    msg = "this is the logging and exception message"
    _LOGGER.error(msg)
    raise Exception(msg)

任何想法表示赞赏!

标签: python

解决方案


在 python 中,最佳实践是使用 logging 模块生成日志文件。对于异常处理,请始终使用 try except 块。

尝试以下方法:

import logging
def a_deeper_level_function():
    try:
        print("I am doing stuff, but it goes wrong. So raising.")

        # but I also want to log here with the same message.
        # so I put my msg in a separate variable to re-use it.

        msg = "this is the logging and exception message"
       _LOGGER.error(msg)
       raise Exception(msg) 
   except Exception as e:
       logging.info(e)
       

推荐阅读