Skip to content
Myr

logging.rst

This file

Path

docs/logging.rst

180 lines · 5.6 KiB

Last changed by

Merge pull request #3243 from DiegoAlbertoTorres/docsDavid Lordbefore adoption6369537

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 has_request_context, request121    from flask.logging import default_handler122123    class RequestFormatter(logging.Formatter):124        def format(self, record):125            if has_request_context():126                record.url = request.url127                record.remote_addr = request.remote_addr128            else:129                record.url = None130                record.remote_addr = None131132            return super().format(record)133134    formatter = RequestFormatter(135        '[%(asctime)s] %(remote_addr)s requested %(url)s\n'136        '%(levelname)s in %(module)s: %(message)s'137    )138    default_handler.setFormatter(formatter)139    mail_handler.setFormatter(formatter)140141142Other Libraries143---------------144145Other libraries may use logging extensively, and you want to see relevant146messages from those logs too. The simplest way to do this is to add handlers147to the root logger instead of only the app logger. ::148149    from flask.logging import default_handler150151    root = logging.getLogger()152    root.addHandler(default_handler)153    root.addHandler(mail_handler)154155Depending on your project, it may be more useful to configure each logger you156care about separately, instead of configuring only the root logger. ::157158    for logger in (159        app.logger,160        logging.getLogger('sqlalchemy'),161        logging.getLogger('other_package'),162    ):163        logger.addHandler(default_handler)164        logger.addHandler(mail_handler)165166167Werkzeug168````````169170Werkzeug logs basic request/response information to the ``'werkzeug'`` logger.171If the root logger has no handlers configured, Werkzeug adds a172:class:`~logging.StreamHandler` to its logger.173174175Flask Extensions176````````````````177178Depending on the situation, an extension may choose to log to179:meth:`app.logger <flask.Flask.logger>` or its own named logger. Consult each180extension's documentation for details.