Rus*_*hal 4 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()
Run Code Online (Sandbox Code Playgroud)
问题是将处理程序添加到哪个记录器。Flask使用werkzeug记录器记录视图功能期间的异常,而不是base app.logger。我必须在werkzeug记录器中注册我的处理程序:
logging.getLogger('werkzeug').addHandler(handler)
Run Code Online (Sandbox Code Playgroud)
另外,我必须将端口包括在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')
)
Run Code Online (Sandbox Code Playgroud)