【问题标题】:How to log stacktrace in json format python如何以json格式python记录stacktrace
【发布时间】:2022-07-07 03:21:13
【问题描述】:

我使用 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"
}

想要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",
  }
}

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

我们是否有任何可用的库来进行堆栈跟踪 json 格式化。还是我们必须编写一个自定义函数?

【问题讨论】:

    标签: python structlog


    【解决方案1】:

    这是一个 sn-p:https://gitlab.com/-/snippets/2284049

    它最终会直接降落在structlog中。

    编辑: https://github.com/hynek/structlog/pull/407 已合并,将成为 v22.1 的一部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-16
      • 2017-10-09
      • 1970-01-01
      • 2020-10-31
      • 2016-01-09
      • 1970-01-01
      • 1970-01-01
      • 2017-02-06
      相关资源
      最近更新 更多