2

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!

NNH
  • 265
  • 3
  • 10
  • Does this answer your question? [How to serialize an Exception](https://stackoverflow.com/questions/45240549/how-to-serialize-an-exception) – aberkb May 11 '22 at 07:19
  • Take a look at the [pprint](https://docs.python.org/3/library/pprint.html) library. Using `pprint.pprint()` will present the variable content in a nice way. – jeandemeusy May 11 '22 at 07:25
  • @aberkb, thanks for your suggestion, but I don't find a "jsonfiy" way to print it. JSON is must here in order to make searches within the error logs – NNH May 11 '22 at 08:09

1 Answers1

2

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()})
NNH
  • 265
  • 3
  • 10