Home > Back-end >  Log related local variable in python on error
Log related local variable in python on error

Time:11-16

Lets say in a production app

a python line res_json = res.json()["data"] trigger the KeyError: 'data'

is there any way that we could effectively smartly log the res in python logger?
For keyerror, we usually want to see whole dict and debug why data atttribute is not inside.

I am getting really tired for "once you discover an exception, you insert a log statement before the line that trigger the error"

In production environment, it is hard to use tool like ipdb to trace back and print out the variable one by one manually.

CodePudding user response:

You can use a try/except with a raise to make sure the exception continues to raise after you've done the site-specific logging:

try:
    res_json = res.json()["data"]
except KeyError as e:
    logger.warning(f"{e}: res = {res}")
    raise
  • Related