Skip to content
Advertisement

python function that logs time & error when a script failed

I’m using python3. I want to print the time a script fails, as well as the corresponding exception in one line. Referring to this link & this one, I tried something like this, but the function didn’t execute. Am I doing something wrong here? Would appreciate suggestions.

import atexit
import datetime

#define function to log when script ends due to error/failure
def f_log(date_and_time, error):
    try:
        print("")
    except:
        print('Script ended at date/time: %s with error %s.' % (date_and_time, error))

import atexit
atexit.register(f_log, date_and_time=datetime.datetime.now(), error=Exception)

print "Deliberate error" # Simple example of an error that should be caught & printed along with time when script fails.

# main body of script continues here
#
#

Advertisement

Answer

Your script has multiple problems. (datetime not imported, useless try/except in f_log, …) The main issue is that a SyntaxError can’t be handled. Try this version instead:

import atexit
import datetime

#define function to log when script ends due to error/failure
def f_log(date_and_time, error):
    print('Script ended at date/time: %s with error %s.' % (date_and_time, error))


atexit.register(f_log, date_and_time=datetime.datetime.now(), error=Exception)

1/0 # Simple example of an error that should be caught & printed along with time when script fails.
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement