小编use*_*811的帖子

如何以 json 格式记录 stacktrace python

我使用 structlog 进行日志记录,并希望以 json 格式打印异常/堆栈跟踪。

目前它没有格式化并且是字符串格式,可读性不是很好

{
  "message": "Error info with an exc", 
  "timestamp": "2022-03-31T13:32:33.928188+00:00", 
  "logger": "__main__", 
  "level": "error", 
  "exception": "Traceback (most recent call last):\n  File \"../../main.py\", line 21, in <module>\n    assert 'foo' == 'bar'\nAssertionError"
}
Run Code Online (Sandbox Code Playgroud)

想要 json 格式的异常,例如

{
  "message": "Error info with an exc", 
  "timestamp": "2022-03-31T13:32:33.928188+00:00", 
  "logger": "__main__", 
  "level": "error", 
  "exception": {
   "File": "../.../main.py",
   "line": 21,
   "function": "<module>",   
   "errorStatement": "assert 'foo' == 'bar'",
   "errorType":"AssertionError",
  }
}
Run Code Online (Sandbox Code Playgroud)

这只是一个小例子,我也使用回溯库并传递在大字符串块中打印的 stackTrace

我们是否有任何可用的库可以进行 stacktrace json 格式化。或者我们必须编写一个自定义函数吗?

python structlog

3
推荐指数
1
解决办法
4930
查看次数

标签 统计

python ×1

structlog ×1