Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way logging exception messages in python

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.

like image 765
wowkin2 Avatar asked Nov 06 '22 15:11

wowkin2


1 Answers

First, the 2 and 4 solution are not working because an exception don't have any message into it.

Then the 1 and 3 are giving the same result :

division by zero

Those are more user-oriented (but not really working with this example).

Finally, the 5 is displaying :

ZeroDivisionError('division by zero')

It is more developer-oriented, if you want to debug code for example, but in that case, you should allow Python to display error by itself so it will be way more explicit.

Hope I answered to your question !

like image 173
B.Medica Avatar answered Nov 14 '22 21:11

B.Medica