How to log stacktrace in json format python

5.2k Views Asked by At

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?

1

There are 1 best solutions below

0
On BEST ANSWER

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.