如何记录我的Python错误?

try:
    do_something()
except:
    # How can I log my exception here, complete with its traceback?

推荐答案

使用except:处理程序/块中的logging.exception来记录当前异常以及跟踪信息,并在消息的前面加上一条消息.

import logging
LOG_FILENAME = '/tmp/logging_example.out'
logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)

logging.debug('This message should go to the log file')

try:
    run_my_stuff()
except:
    logging.exception('Got exception on main handler')
    raise

现在查看日志(log)文件,/tmp/logging_example.out:

DEBUG:root:This message should go to the log file
ERROR:root:Got exception on main handler
Traceback (most recent call last):
  File "/tmp/teste.py", line 9, in <module>
    run_my_stuff()
NameError: name 'run_my_stuff' is not defined

Python相关问答推荐

运行回文查找器代码时发生错误:[类型错误:builtin_index_or_system对象不可订阅]

如何使用matplotlib在Python中使用规范化数据和原始t测试值创建组合热图?

如何避免Chained when/then分配中的Mypy不兼容类型警告?

查找两极rame中组之间的所有差异

如何在python xsModel库中定义一个可选[December]字段,以产生受约束的SON模式

删除字符串中第一次出现单词后的所有内容

如何在python polars中停止otherate(),当使用when()表达式时?

Streamlit应用程序中的Plotly条形图中未正确显示Y轴刻度

如何启动下载并在不击中磁盘的情况下呈现响应?

在不同的帧B中判断帧A中的子字符串,每个帧的大小不同

跳过嵌套JSON中的级别并转换为Pandas Rame

使用Openpyxl从Excel中的折线图更改图表样式

在numpy数组中寻找楼梯状 struct

Js的查询结果可以在PC Chrome上显示,但不能在Android Chrome、OPERA和EDGE上显示,而两者都可以在Firefox上运行

获取PANDA GROUP BY转换中的组的名称

如何将返回引用的函数与pybind11绑定?

对数据帧进行分组,并按组间等概率抽样n行

.awk文件可以使用子进程执行吗?

如何在Python中实现高效地支持字典和堆操作的缓存?

当lambda函数作为参数传递时,pyo3执行