Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

What is the best way to log a Python exception?

In the code below

try:
    print 'toy' + 6
except Exception as e:
    print e

I want to log the exception. How do I do that?


1 Answer
Rajendra Dharmkar

We import the logging module and then use the logging.exception method to create a log of the python exception.

import logging
try:
print 'toy' + 6
except Exception as e:
logging.exception("This is an exception log")

We get the following output

ERROR:root:This is an exception log
Traceback (most recent call last):
File "C:/Users/TutorialsPoint1/PycharmProjects/TProg/Exception handling/loggingerror1.py", line 3, in <module>
print 'toy' + 6
TypeError: cannot concatenate 'str' and 'int' objects

It is noted that in Python 3 we must call the logging.exception method just inside the except part. If we call this method in any other place we may get a weird exception as per alert by python docs.

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.