Posts: 25
Joined: Sun Oct 14, 2012 4:51 pm
Location: Hertfordshire

Logging Python Traceback

Fri Nov 15, 2019 7:31 pm

I have a headless pi in my shed reading temp and humidity.
Every now and then the python program fails.
Is there a way I can capture the Traceback and log it to a file?

I think I might have found the answer in "Introducing Python". There is a module called 'logging' and from a very brief look appears to do what I want. :)

I'll edit this post later.

Posts: 383
Joined: Fri Feb 13, 2015 3:18 pm

Re: Logging Python Traceback

Mon Nov 18, 2019 7:32 am

From the Python interpreter, you will know the line that the error is occurring in and also the exception type.
I would encapsulate that line (or lines) in a try except finally block. My example is for connecting the SMTP server.

Code: Select all

        try :
            server=smtplib.SMTP('smtp-mail.outlook.com', 587)
        except (gaierror):
            print("GAI error")
        finally :
            print("Got to finally")
That way you can trap the error, take corrective action and have your program keep running...

Return to “Python”