Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to log Flask exceptions with SMTP handler

I am attempting to get an email sent to me any time an error occurs in my Flask application. The email is not being sent despite the handler being registered. I used smtplib to verify that my SMTP login details are correct. The error is displayed in Werkzeug's debugger, but no emails are sent. How do I log exceptions that occur in my app?

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()
like image 337
Rushy Panchal Avatar asked Mar 14 '23 22:03

Rushy Panchal


1 Answers

The issue was which logger the handler was added to. Flask uses the werkzeug logger to log exceptions during view functions, not the base app.logger. I had to register my handler with the werkzeug logger:

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

In addition, I had to include the port in 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')
)
like image 130
Rushy Panchal Avatar answered Mar 23 '23 04:03

Rushy Panchal