简体   繁体   中英

How to log stacktrace in json format python

Im using structlog for logging and want the exception/stacktrace to be printed in json format.

Currently its not formatted and in string format which is not very readable

{
  "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"
}

Wanted exception in json format like

{
  "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",
  }
}

This is just a small example I am aslo using traceback library and passing the stackTrace which gets printed in large string block

Do we have any library available which does stacktrace json formatting. or do we have to write a custom function?

Here is a snippet which does that: https://gitlab.com/-/snippets/2284049

It will eventually land directly in structlog.

edit: https://github.com/hynek/structlog/pull/407 has been merged and will be part of v22.1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM