无法使用SMTP处理程序记录Flask异常

时间:2015-08-29 04:52:46

标签: python logging flask

我试图在我的Flask应用程序中发生错误时发送电子邮件给我。尽管处理程序已注册,但仍未发送电子邮件。我使用smtplib来验证我的SMTP登录详细信息是否正确。错误显示在Werkzeug的调试器中,但不发送任何电子邮件。如何记录我的应用程序中发生的异常?

import logging
from logging.handlers import SMTPHandler
from flask import Flask

app = Flask(__name__)
app.debug = True
app.config['PROPAGATE_EXCEPTIONS'] = True

if app.debug:
    logging.basicConfig(level=logging.INFO)

    # all of the $ names have actual values
    handler = SMTPHandler(
        mailhost = 'smtp.mailgun.org',
        fromaddr = 'Application Bug Reporter <$mailgun_email_here>',
        toaddrs = ['$personal_email_here'],
        subject = 'Test Application Logging Email',
        credentials = ('$mailgun_email_here', '$mailgun_password_here')
    )
    handler.setLevel(logging.ERROR)
    app.logger.addHandler(handler)

@app.route('/')
def index():
    raise Exception('Hello, World!')  # should trigger an email

app.run()

1 个答案:

答案 0 :(得分:4)

问题在于添加了处理程序的记录器。 Flask使用werkzeug记录器在视图函数中记录异常,而不是基础app.logger。我必须使用werkzeug记录器注册我的处理程序:

logging.getLogger('werkzeug').addHandler(handler)

此外,我必须在mailhost中包含端口:

handler = SMTPHandler(
    mailhost=('smtp.mailgun.org', 587),
    fromaddr='Application Bug Reporter <$mailgun_email_here>',
    toaddrs=['$personal_email_here'],
    subject='Test Application Logging Email',
    credentials=('$mailgun_email_here', '$mailgun_password_here')
)