Logging
When you want to configure logging for your project, you should do it as soonas possible when the program starts. If app.logger
is accessed before logging is configured, it will add a default handler. Ifpossible, configure logging before creating the application object.
This example uses to create a loggingconfiguration similar to Flask’s default, except for all logs:
If you configured logging after accessing, and need to remove the defaulthandler, you can import and remove it:
- from flask.logging import default_handler
- app.logger.removeHandler(default_handler)
When running the application on a remote server for production, you probablywon’t be looking at the log messages very often. The WSGI server will probablysend log messages to a file, and you’ll only check that file if a user tellsyou something went wrong.
To be proactive about discovering and fixing bugs, you can configure a to send an email when errors and higherare logged.
- import logging
- from logging.handlers import SMTPHandler
- mail_handler = SMTPHandler(
- mailhost='127.0.0.1',
- fromaddr='[email protected]',
- 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)
This requires that you have an SMTP server set up on the same server. See thePython docs for more information about configuring the handler.
- from flask import has_request_context, request
- from flask.logging import default_handler
- class RequestFormatter(logging.Formatter):
- def format(self, record):
- if has_request_context():
- record.url = request.url
- record.remote_addr = request.remote_addr
- record.url = None
- record.remote_addr = None
- return super().format(record)
- formatter = RequestFormatter(
- '[%(asctime)s] %(remote_addr)s requested %(url)s\n'
- '%(levelname)s in %(module)s: %(message)s'
- )
- default_handler.setFormatter(formatter)
- mail_handler.setFormatter(formatter)
Other libraries may use logging extensively, and you want to see relevantmessages from those logs too. The simplest way to do this is to add handlersto the root logger instead of only the app logger.
Depending on your project, it may be more useful to configure each logger youcare about separately, instead of configuring only the root logger.
- for logger in (
- app.logger,
- logging.getLogger('sqlalchemy'),
- logging.getLogger('other_package'),
- ):
- logger.addHandler(default_handler)
Werkzeug logs basic request/response information to the 'werkzeug'
logger.If the root logger has no handlers configured, Werkzeug adds a to its logger.
Depending on the situation, an extension may choose to log to or its own named logger. Consult eachextension’s documentation for details.