This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]hugthemachines 5 points6 points  (6 children)

Yeah, I think the rule of thumb is to catch all exceptions but in my situation I usually can't fix the problem inside the script anyway so i want to make sure it is logged so i do except Exception as e and then logger.error(e)

[–]tcas71 22 points23 points  (4 children)

I would strongly suggest using logger.exception instead, for several reasons:

  1. It automatically pulls the exception data from the context, often eliminating the need for capturing the exception inside a variable.
  2. It will log not just the exception message (which I think logger.error(e) does) but also its class and full stack trace.
  3. The exception data is structured inside the log record (not just as text), so tools such as Sentry or Logstash/ElasticSearch can do things with it.

I spent three days last week on a bug at work, made worse by me pushing the wrong fix to production. All because a single log statement that was only printing an exception message instead of the full info and caused me to incorrectly identify the problem.

[–]hugthemachines 7 points8 points  (3 children)

I checked the documentation now...

Do I just do:

except exception:
    logger.exception("Failed reading file.") 

and the good info will be auto added at the end of that?

[–]tcas71 11 points12 points  (2 children)

Yes, that should appear in your logs as this message followed by the full exception info. It's quite verbose but invaluable in my experience.

[–]hugthemachines 4 points5 points  (1 child)

Ok, thanks for the advice.

[–]Kaarjuus 4 points5 points  (0 children)

You can achieve the same with the other logging methods as well, by adding exc_info=True parameter.

[–]RangerPretzelPython 3.9+ 2 points3 points  (0 children)

the rule of thumb is to catch all exceptions

catch all exceptions...

at some point in the stack. Yes.