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.