Skip to content
Myr

logging.rst

This file

Path

docs/logging.rst

175 lines · 5.5 KiB

Last changed by

Merge pull request #2786 from greyli/patch-9Hsiaoming Yangbefore adoptioncae0378

History of this file

Take it

1.. _logging:23Logging4=======56Flask uses standard Python :mod:`logging`. All Flask-related messages are7logged under the ``'flask'`` logger namespace.8:meth:`Flask.logger <flask.Flask.logger>` returns the logger named9``'flask.app'``, and can be used to log messages for your application. ::1011    @app.route('/login', methods=['POST'])12    def login():13        user = get_user(request.form['username'])1415        if user.check_password(request.form['password']):16            login_user(user)17            app.logger.info('%s logged in successfully', user.username)18            return redirect(url_for('index'))19        else:20            app.logger.info('%s failed to log in', user.username)21            abort(401)222324Basic Configuration25-------------------2627When you want to configure logging for your project, you should do it as soon28as possible when the program starts. If :meth:`app.logger <flask.Flask.logger>`29is accessed before logging is configured, it will add a default handler. If30possible, configure logging before creating the application object.3132This example uses :func:`~logging.config.dictConfig` to create a logging33configuration similar to Flask's default, except for all logs::3435    from logging.config import dictConfig3637    dictConfig({38        'version': 1,39        'formatters': {'default': {40            'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',41        }},42        'handlers': {'wsgi': {43            'class': 'logging.StreamHandler',44            'stream': 'ext://flask.logging.wsgi_errors_stream',45            'formatter': 'default'46        }},47        'root': {48            'level': 'INFO',49            'handlers': ['wsgi']50        }51    })5253    app = Flask(__name__)545556Default Configuration57`````````````````````5859If you do not configure logging yourself, Flask will add a60:class:`~logging.StreamHandler` to :meth:`app.logger <flask.Flask.logger>`61automatically. During requests, it will write to the stream specified by the62WSGI server in ``environ['wsgi.errors']`` (which is usually63:data:`sys.stderr`). Outside a request, it will log to :data:`sys.stderr`.646566Removing the Default Handler67````````````````````````````6869If you configured logging after accessing70:meth:`app.logger <flask.Flask.logger>`, and need to remove the default71handler, you can import and remove it::7273    from flask.logging import default_handler7475    app.logger.removeHandler(default_handler)767778Email Errors to Admins79----------------------8081When running the application on a remote server for production, you probably82won't be looking at the log messages very often. The WSGI server will probably83send log messages to a file, and you'll only check that file if a user tells84you something went wrong.8586To be proactive about discovering and fixing bugs, you can configure a87:class:`logging.handlers.SMTPHandler` to send an email when errors and higher88are logged. ::8990    import logging91    from logging.handlers import SMTPHandler9293    mail_handler = SMTPHandler(94        mailhost='127.0.0.1',95        fromaddr='server-error@example.com',96        toaddrs=['admin@example.com'],97        subject='Application Error'98    )99    mail_handler.setLevel(logging.ERROR)100    mail_handler.setFormatter(logging.Formatter(101        '[%(asctime)s] %(levelname)s in %(module)s: %(message)s'102    ))103104    if not app.debug:105        app.logger.addHandler(mail_handler)106107This requires that you have an SMTP server set up on the same server. See the108Python docs for more information about configuring the handler.109110111Injecting Request Information112-----------------------------113114Seeing more information about the request, such as the IP address, may help115debugging some errors. You can subclass :class:`logging.Formatter` to inject116your own fields that can be used in messages. You can change the formatter for117Flask's default handler, the mail handler defined above, or any other118handler. ::119120    from flask import request121    from flask.logging import default_handler122123    class RequestFormatter(logging.Formatter):124        def format(self, record):125            record.url = request.url126            record.remote_addr = request.remote_addr127            return super(RequestFormatter, self).format(record)128129    formatter = RequestFormatter(130        '[%(asctime)s] %(remote_addr)s requested %(url)s\n'131        '%(levelname)s in %(module)s: %(message)s'132    )133    default_handler.setFormatter(formatter)134    mail_handler.setFormatter(formatter)135136137Other Libraries138---------------139140Other libraries may use logging extensively, and you want to see relevant141messages from those logs too. The simplest way to do this is to add handlers142to the root logger instead of only the app logger. ::143144    from flask.logging import default_handler145146    root = logging.getLogger()147    root.addHandler(default_handler)148    root.addHandler(mail_handler)149150Depending on your project, it may be more useful to configure each logger you151care about separately, instead of configuring only the root logger. ::152153    for logger in (154        app.logger,155        logging.getLogger('sqlalchemy'),156        logging.getLogger('other_package'),157    ):158        logger.addHandler(default_handler)159        logger.addHandler(mail_handler)160161162Werkzeug163````````164165Werkzeug logs basic request/response information to the ``'werkzeug'`` logger.166If the root logger has no handlers configured, Werkzeug adds a167:class:`~logging.StreamHandler` to its logger.168169170Flask Extensions171````````````````172173Depending on the situation, an extension may choose to log to174:meth:`app.logger <flask.Flask.logger>` or its own named logger. Consult each175extension's documentation for details.