What is most correct way of logging exceptions in Python?
Some people log just e
, another logs attribute e.message
(but it can be missing for some exceptions).
One use str()
to capture description of exception, but it doesn't contain error type and sometimes are useless without that.
Actually repr()
will return both error type and description but it is not so popular (in projects that I saw).
One more related question: how this affect services that collect and group errors/alerts like Sentry. They should also contain some information about concrete error.
So want to open this discussion again: which way of logging exceptions is the best to use?
def foo():
""" Method that can raise various types of exceptions """
1/0 # just for example
try:
foo()
except Exception as e:
logger.exception('Error occurred during execution: %s', e) # 1
logger.exception('Error occurred during execution: %s', e.message) # 2
logger.exception('Error occurred during execution: %s', str(e)) # 3
logger.exception('Error occurred during execution: %s', str(e.message)) # 4
logger.exception('Error occurred during execution: %s', repr(e)) # 5
Found one old discussion here, but it doesn't use logging
library and maybe something changed from that moment.
P.S. I know how to get trace-back and any other related information. The question here what should be the general rule for logging exceptions and errors.
e
to message as argument? Maybe I'll need to update this question with also case of uselogger.error(...)
– Bassoe
, but you can do it, the exceptionn's message will be logged, followed by the traceback of the error. And I don't know for Sentry, I never used it... – Widdershinslogger.exception()
already so the error name and message (and the full traceback) will get logged anyway. – Kawasaki