python - How to make SMTPHandler not block -
i installed local smtp server , used logging.handlers.smtphandler
log exception using code:
import logging import logging.handlers import time gm = logging.handlers.smtphandler(("localhost", 25), 'info@somewhere.com', ['my_email@gmail.com'], 'hello exception!',) gm.setlevel(logging.error) logger.addhandler(gm) t0 = time.clock() try: 1/0 except: logger.exception('testest') print time.clock()-t0
it took more 1sec complete, blocking python script whole time. how come? how can make not block script?
here's implementation i'm using, based on this gmail adapted smtphandler.
took part sends smtp , placed in different thread.
import logging.handlers import smtplib threading import thread def smtp_at_your_own_leasure(mailhost, port, username, password, fromaddr, toaddrs, msg): smtp = smtplib.smtp(mailhost, port) if username: smtp.ehlo() # tls add line smtp.starttls() # tls add line smtp.ehlo() # tls add line smtp.login(username, password) smtp.sendmail(fromaddr, toaddrs, msg) smtp.quit() class threadedtlssmtphandler(logging.handlers.smtphandler): def emit(self, record): try: import string # tls add line try: email.utils import formatdate except importerror: formatdate = self.date_time port = self.mailport if not port: port = smtplib.smtp_port msg = self.format(record) msg = "from: %s\r\nto: %s\r\nsubject: %s\r\ndate: %s\r\n\r\n%s" % ( self.fromaddr, string.join(self.toaddrs, ","), self.getsubject(record), formatdate(), msg) thread = thread(target=smtp_at_your_own_leasure, args=(self.mailhost, port, self.username, self.password, self.fromaddr, self.toaddrs, msg)) thread.start() except (keyboardinterrupt, systemexit): raise except: self.handleerror(record)
usage example:
logger = logging.getlogger() gm = threadedtlssmtphandler(("smtp.gmail.com", 587), 'bugs@my_company.com', ['admin@my_company.com'], 'error found!', ('my_company_account@gmail.com', 'top_secret_gmail_password')) gm.setlevel(logging.error) logger.addhandler(gm) try: 1/0 except: logger.exception('fffffffffffffffffffffffuuuuuuuuuuuuuuuuuuuuuu-')
Comments
Post a Comment