'Python - How to print error with JSON format
I'm new to Python, but as much as I search - I don't find a "jsonfiy" method for printing an error to the logs.
the way I'm printing today:
except Exception as e:
print(type(e))
print(e)
print(traceback.format_exc())
This way I get all needed data from the exception, but I must represent it in a JSON format.
Any help will be appreciated!
Solution 1:[1]
I finally found the answer to my question, using python-json-logger, in my case I used it within Flask app, so the way to configure logger to use JSON format is this:
formatter = jsonlogger.JsonFormatter('%(asctime) %(levelname) %(message)')
app.logger.handlers[0].setFormatter(formatter)
Then I used app logger to log an error with JSON format like this:
except Exception as e:
app.logger.error({"error": type(e).__name__, "message": e, "at": traceback.format_exc()})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | NNH |