[Flask] Where to set up logging in large flask app
Hippo
badrihippo at gmail.com
Fri Jul 12 01:54:34 EDT 2019
Hello all,
I have a Flask app split into many components like views.py, forms.py,
models.py, and so on. The app is in version control, and I'm using the
instance folder (with a config.py inside) to handle the local,
server-specific settings. The main Flask() object is defined in __init__.py.
Now I'm setting up email notifications for error logging, using
instructions from this documentation page
<https://flask.palletsprojects.com/en/1.1.x/logging/#email-errors-to-admins>,
but can't decide where to paste the code:
import logging
from logging.handlers import SMTPHandler
mail_handler = SMTPHandler(
mailhost='127.0.0.1',
fromaddr='server-error at example.com',
toaddrs=['admin at example.com'],
subject='Application Error'
)
mail_handler.setLevel(logging.ERROR)
mail_handler.setFormatter(logging.Formatter(
'[%(asctime)s] %(levelname)s in %(module)s: %(message)s'
))
if not app.debug:
app.logger.addHandler(mail_handler)
Normally, this would go in instance/config.py. However, the last two lines
need the app object, which is not imported to config (since the import goes
the other way round).
One option I thought of is to make the whole mail handler into a
setting (ERROR_EMAIL_HANDLER
= SMTPHandler(...)), and then add the following lines to __init__.py where
I've defined the app:
if app.settings.get('ERROR_EMAIL_HANDLER') and not app.debug:
app.logger.addHandler(ERROR_EMAIL_HANDLER)
What do you think of this solution? Anything more elegant to suggest?
Thanks in advance,
Badri
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/flask/attachments/20190712/84218f36/attachment.html>
More information about the Flask
mailing list