Question

I have Flask setup to email me when an error occurs but I'd like to include the UserAgent in that email. Is that possible? I didn't see it in The docs.

EDIT: The link says more stuff can be found in the official documentation but isn't that the official documentation? (flask.readthedocs.org says the same thing)

Was it helpful?

Solution

I discovered how to do this deep in this article. You'll need to set up a new filter to add the user-agent to the record. It seems that at filter stage, you can use the request object to get at what you're looking for. So you're not actually filtering anything out, but adding more to the log record. Functional example:

from flask import Flask, request

app = Flask(__name__)

if not app.debug:
    import logging
    from logging.handlers import SMTPHandler

    class ContextualFilter(logging.Filter):
        def filter(self, log_record):
            log_record.user_agent = request.user_agent
            return True

    context_provider = ContextualFilter()
    app.logger.addFilter(context_provider)
    mail_handler = SMTPHandler('127.0.0.1', 'apperror@example.com',
                    app.config['ADMINS'], 'Application failed')
    mail_handler.setFormatter(logging.Formatter("""
Message type:       %(levelname)s
Location:           %(pathname)s:%(lineno)d
Module:             %(module)s
Function:           %(funcName)s
Time:               %(asctime)s
User-Agent:         %(user_agent)s

Message:

%(message)s
"""))
    mail_handler.setLevel(logging.ERROR)
    app.logger.addHandler(mail_handler)

Using this, I was able to get emails sent to myself for error logs.

OTHER TIPS

I think your answer was one click away in the docs. Check out this entry on custom email message formatting. Use the example code snipped, adding an import of the Flask request object. Get the string itself using methods from this question.

from logging import Formatter
from flask import request
mail_handler.setFormatter(Formatter('''
Message type:       %(levelname)s
Location:           %(pathname)s:%(lineno)d
Module:             %(module)s
Function:           %(funcName)s
Time:               %(asctime)s
UserAgent:          %s

Message:

%(message)s
''' % flask.request.user_agent.string))

This may not be perfect (especially my string formatting code) but hopefully that article points you in the right direction.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top