Page 1 of 1

Logging Python Traceback

Posted: Fri Nov 15, 2019 7:31 pm
by Hcgrant
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.

Re: Logging Python Traceback

Posted: Mon Nov 18, 2019 7:32 am
by MarkDH102
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('', 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...