我试图在我的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()
答案 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')
)