Page 1 of 1

Error Logging - Help

Posted: Sun Jan 19, 2014 7:57 am
by robbo100
I have just finished writing some code in Python which is designed to run on my RPi without a monitor connected. I expect to need to keep the RPi running this script for upto 60 days.

When I run it via SSH, everything works fine, but now that I have set the code to run at boot-up, I have discovered that it is crashing after 10 hours or so.

Is there any command that I can use, which will log ANY error for the whole script (any def or thread) so that I can track the problem down?

Thanks

Robbo100.

Re: Error Logging - Help

Posted: Sun Jan 19, 2014 8:50 am
by ZacharyIgielman
robbo100 wrote:I have just finished writing some code in Python which is designed to run on my RPi without a monitor connected. I expect to need to keep the RPi running this script for upto 60 days.

When I run it via SSH, everything works fine, but now that I have set the code to run at boot-up, I have discovered that it is crashing after 10 hours or so.

Is there any command that I can use, which will log ANY error for the whole script (any def or thread) so that I can track the problem down?

Thanks

Robbo100.

Code: Select all

try:
    #your code
except Exception,e:
    print str(e)

Re: Error Logging - Help

Posted: Sun Jan 19, 2014 9:52 am
by robbo100
Presumably I can use the "print >>" command to send the string to an open file?

Re: Error Logging - Help

Posted: Sun Jan 19, 2014 10:25 am
by ZacharyIgielman
robbo100 wrote:Presumably I can use the "print >>" command to send the string to an open file?
Yes you can!

If you want the whole traceback:

Code: Select all

import traceback

try:
    #code
except Exception, e:
    print str(e) #you could also print to file here
    traceback.print_exc()

Re: Error Logging - Help

Posted: Sun Jan 19, 2014 10:41 am
by robbo100
Thanks mate

Re: Error Logging - Help

Posted: Sun Jan 19, 2014 12:57 pm
by elParaguayo
If I've got a script I leave running, I either use the logging module as I can set various debug levels, or do something simple like this:

Code: Select all

from datetime import datetime

def scriptdebug(errormessage):
    with open("error.log", "a") as errorlog:
        errorlog.write("%s\t%s\n" % (datetime.strftime(datetime.now(),
                                     "%d-%m-%y %H:%M"),
                                     errormessage))
You can then use it as Zachary suggests:

Code: Select all

try:
    #code
except Exception, e:
    scriptdebug(e)
Error messages will be posted to the "error.log" file with a timestamp of the current date and time.

EDIT: Should also add that if you want to use this method in conjunction with the traceback module as Zachary suggested (and the advantage of this is that you do get more detail on the error) then, assuming you've imported the traceback module, you'd call the scriptdebug method like this:

Code: Select all

scriptdebug(traceback.format_exc())