Skip to content
Myr

logging.rst

This file

Path

docs/logging.rst

183 lines · 5.8 KiB

Last changed by

Not known.

History of this file

Take it

1Logging2=======34Flask uses standard Python :mod:`logging`. Messages about your Flask5application are logged with :meth:`app.logger <flask.Flask.logger>`,6which takes the same name as :attr:`app.name <flask.Flask.name>`. This7logger can also be used to log your own messages.89.. code-block:: python1011    @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)2223If you don't configure logging, Python's default log level is usually24'warning'. Nothing below the configured level will be visible.252627Basic Configuration28-------------------2930When you want to configure logging for your project, you should do it as soon31as possible when the program starts. If :meth:`app.logger <flask.Flask.logger>`32is accessed before logging is configured, it will add a default handler. If33possible, configure logging before creating the application object.3435This example uses :func:`~logging.config.dictConfig` to create a logging36configuration similar to Flask's default, except for all logs::3738    from logging.config import dictConfig3940    dictConfig({41        'version': 1,42        'formatters': {'default': {43            'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',44        }},45        'handlers': {'wsgi': {46            'class': 'logging.StreamHandler',47            'stream': 'ext://flask.logging.wsgi_errors_stream',48            'formatter': 'default'49        }},50        'root': {51            'level': 'INFO',52            'handlers': ['wsgi']53        }54    })5556    app = Flask(__name__)575859Default Configuration60`````````````````````6162If you do not configure logging yourself, Flask will add a63:class:`~logging.StreamHandler` to :meth:`app.logger <flask.Flask.logger>`64automatically. During requests, it will write to the stream specified by the65WSGI server in ``environ['wsgi.errors']`` (which is usually66:data:`sys.stderr`). Outside a request, it will log to :data:`sys.stderr`.676869Removing the Default Handler70````````````````````````````7172If you configured logging after accessing73:meth:`app.logger <flask.Flask.logger>`, and need to remove the default74handler, you can import and remove it::7576    from flask.logging import default_handler7778    app.logger.removeHandler(default_handler)798081Email Errors to Admins82----------------------8384When running the application on a remote server for production, you probably85won't be looking at the log messages very often. The WSGI server will probably86send log messages to a file, and you'll only check that file if a user tells87you something went wrong.8889To be proactive about discovering and fixing bugs, you can configure a90:class:`logging.handlers.SMTPHandler` to send an email when errors and higher91are logged. ::9293    import logging94    from logging.handlers import SMTPHandler9596    mail_handler = SMTPHandler(97        mailhost='127.0.0.1',98        fromaddr='server-error@example.com',99        toaddrs=['admin@example.com'],100        subject='Application Error'101    )102    mail_handler.setLevel(logging.ERROR)103    mail_handler.setFormatter(logging.Formatter(104        '[%(asctime)s] %(levelname)s in %(module)s: %(message)s'105    ))106107    if not app.debug:108        app.logger.addHandler(mail_handler)109110This requires that you have an SMTP server set up on the same server. See the111Python docs for more information about configuring the handler.112113114Injecting Request Information115-----------------------------116117Seeing more information about the request, such as the IP address, may help118debugging some errors. You can subclass :class:`logging.Formatter` to inject119your own fields that can be used in messages. You can change the formatter for120Flask's default handler, the mail handler defined above, or any other121handler. ::122123    from flask import has_request_context, request124    from flask.logging import default_handler125126    class RequestFormatter(logging.Formatter):127        def format(self, record):128            if has_request_context():129                record.url = request.url130                record.remote_addr = request.remote_addr131            else:132                record.url = None133                record.remote_addr = None134135            return super().format(record)136137    formatter = RequestFormatter(138        '[%(asctime)s] %(remote_addr)s requested %(url)s\n'139        '%(levelname)s in %(module)s: %(message)s'140    )141    default_handler.setFormatter(formatter)142    mail_handler.setFormatter(formatter)143144145Other Libraries146---------------147148Other libraries may use logging extensively, and you want to see relevant149messages from those logs too. The simplest way to do this is to add handlers150to the root logger instead of only the app logger. ::151152    from flask.logging import default_handler153154    root = logging.getLogger()155    root.addHandler(default_handler)156    root.addHandler(mail_handler)157158Depending on your project, it may be more useful to configure each logger you159care about separately, instead of configuring only the root logger. ::160161    for logger in (162        app.logger,163        logging.getLogger('sqlalchemy'),164        logging.getLogger('other_package'),165    ):166        logger.addHandler(default_handler)167        logger.addHandler(mail_handler)168169170Werkzeug171````````172173Werkzeug logs basic request/response information to the ``'werkzeug'`` logger.174If the root logger has no handlers configured, Werkzeug adds a175:class:`~logging.StreamHandler` to its logger.176177178Flask Extensions179````````````````180181Depending on the situation, an extension may choose to log to182:meth:`app.logger <flask.Flask.logger>` or its own named logger. Consult each183extension's documentation for details.