Currently I have a script defined like so:
import traceback
import logging
import time
logging.basicConfig(level=loggings.DEBUG)
logger=logging.getLogger(__name__)
if __name__ == '__main__':
try:
main_code()
except Exception as e:
logger.debug(traceback.format_exc())
error = traceback.format_exc()
with smtplib.SMTP("mailhub.global.company.com") as mailServer:
msg = MIMEMultipart('related')
msg['Subject'] = Header(u'Test', 'utf-8')
msg['X-Priority'] = '2'
body = "Delivery Failure, the following exception occurred:\n\n" + str(error)
msg.attach(MIMEText(body, 'plain'))
mailServer.sendmail("email@gmail.com", ["email@gmail.com"], msg.as_string())
mailServer.quit()
print("Exception occurred- delivery failure email sent")
This works perfectly in the sense that if there is an error, I receive an email with traceback.
I attempted to add a "retry" to the code in case of failure, so that it tries 5 times, with 5 seconds in between like so:
if __name__ == '__main__':
for attempt in range(5):
try:
main_code()
except Exception as e:
print("Error occurred, retrying in 5 seconds!")
time.sleep(5)
continue
else:
break
else:
logger.debug(traceback.format_exc())
error = traceback.format_exc()
with smtplib.SMTP("mailhub.global.company.com") as mailServer:
msg = MIMEMultipart('related')
msg['Subject'] = Header(u'Test', 'utf-8')
msg['X-Priority'] = '2'
body = "Delivery Failure, the following exception occurred:\n\n" + str(error)
msg.attach(MIMEText(body, 'plain'))
mailServer.sendmail("email@gmail.com", ["email@gmail.com"], msg.as_string())
mailServer.quit()
print("Exception occurred- delivery failure email sent")
However, for some reason when I receive a delivery failure email now, all it says is: Delivery Failure, the following exception occurred: NoneType: None
Any idea how to bring back the traceback to the error in the email that is sent?
The exception is "cleaned up" (destroyed) when you leave the except
block, so that functions in the traceback
module cannot see it by the time you get to the final else
block. You probably want to move error = traceback.format_exc()
into the except
block (and also pass error
to logger.debug()
).