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!

3
  • 1
    Does this answer your question? How to serialize an Exception Commented May 11, 2022 at 7:19
  • Take a look at the pprint library. Using pprint.pprint(<dict_like_var>) will present the variable content in a nice way. Commented May 11, 2022 at 7: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 Commented May 11, 2022 at 8:09

1 Answer 1

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()})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.