python - 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 中,最佳实践是使用 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)
推荐阅读
- java - 一行java特定列的最大值
- ms-access - MS Access 获取数据表中的子行数
- javascript - React - 重叠 css 文件
- reactjs - 事件在 axios 拦截器内触发两次
- python - Discord 机器人加入/离开
- interface - 无法弄清楚 MPS 错误:“角色 XY 中的孩子不属于概念 X”
- rundeck - Rundeck 作业返回 curl: (52) 来自服务器的空回复
- c - 我可以刷新多行输出吗?
- python - 一句话写出嵌套的for循环
- javascript - javascript raycaster 引擎中的鱼眼协作