logging.py

Official Document

None.

Overview

This is a simple module which includes some basic logging functions in Flask. Note that this module slightly depends on global.py.

Details

wsgi_errors_stream()

The method wsgi_errors_stream() returns an output stream object, and the default stream is sys.stderr if the request is not active. It is noticeable that the decorator @LocalProxy indicates that we can take wsgi_errors_steam as a property, and each time we use this property, we can always get the latest result.

from .globals import request

@LocalProxy
def wsgi_errors_stream():
    return request.environ["wsgi.errors"] if request else sys.stderr

Also, it is implied that the default_handler is dynamic, and it can change the output stream based on current request situation.

default_handler = logging.StreamHandler(wsgi_errors_stream)
default_handler.setFormatter(
    logging.Formatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s")
)

has_level_handler(logger)

The method has_level_handler(logger) returns True if there is at least a handler in the logging chain will handle the given logger’s records. Note that a logging level has its corresponding int value, for example, logging.DEBUG has value 10, logging.ERROR has value 40, and logging.NOTSET has value 0. A larger number means this level is more important, and handler.level <= level if a handler’s level value is less than the logger’s, then this handler can deal with its records.

import logging

def has_level_handler(logger):
    level = logger.getEffectiveLevel()
    current = logger

    while current:
        if any(handler.level <= level for handler in current.handlers):
            return True

        if not current.propagate:
            break

        current = current.parent

    return False

_has_config(logger)

The underscore in the beginning shows that _has_config(logger) is a module-private method. This method returns True if the logger is well-configured, and the rule is here: if a logger’s level has been set, or it has any handler, or it has any filter, or it cannot propagate, then the logger is well-configured. Note that the brackets after the keyword return can be ignored, for example, (True or False) and True or False present the same thing.

def _has_config(logger):
    return (
        logger.level != logging.NOTSET
        or logger.handlers
        or logger.filters
        or not logger.propagate
    )

create_logger(app)

create_logger(app) method’s functionality is simple: if the logger of app is not configured, then assign a default DEBUG level and a default DEBUG handler to it. Note that if someone use old names, then a warning message will be displayed.

def create_logger(app):
    logger = logging.getLogger(app.name)

    # 1.1.0 changes name of logger, warn if config is detected for old
    # name and not new name
    for old_name in ("flask.app", "flask"):
        old_logger = logging.getLogger(old_name)

        if _has_config(old_logger) and not _has_config(logger):
            warnings.warn(
                "'app.logger' is named '{name}' for this application,"
                " but configuration was found for '{old_name}', which"
                " no longer has an effect. The logging configuration"
                " should be moved to '{name}'.".format(name=app.name, old_name=old_name)
            )
            break

    if app.debug and not logger.level:
        logger.setLevel(logging.DEBUG)

    if not has_level_handler(logger):
        logger.addHandler(default_handler)

    return logger

Note

This is a simple module in Flask project which does not include any web application logics.

Source Code

# -*- coding: utf-8 -*-
"""
flask.logging
~~~~~~~~~~~~~

:copyright: 2010 Pallets
:license: BSD-3-Clause
"""
from __future__ import absolute_import

import logging
import sys
import warnings

from werkzeug.local import LocalProxy

from .globals import request


@LocalProxy
def wsgi_errors_stream():
    """Find the most appropriate error stream for the application. If a request
    is active, log to ``wsgi.errors``, otherwise use ``sys.stderr``.

    If you configure your own :class:`logging.StreamHandler`, you may want to
    use this for the stream. If you are using file or dict configuration and
    can't import this directly, you can refer to it as
    ``ext://flask.logging.wsgi_errors_stream``.
    """
    return request.environ["wsgi.errors"] if request else sys.stderr


def has_level_handler(logger):
    """Check if there is a handler in the logging chain that will handle the
    given logger's :meth:`effective level <~logging.Logger.getEffectiveLevel>`.
    """
    level = logger.getEffectiveLevel()
    current = logger

    while current:
        if any(handler.level <= level for handler in current.handlers):
            return True

        if not current.propagate:
            break

        current = current.parent

    return False


#: Log messages to :func:`~flask.logging.wsgi_errors_stream` with the format
#: ``[%(asctime)s] %(levelname)s in %(module)s: %(message)s``.
default_handler = logging.StreamHandler(wsgi_errors_stream)
default_handler.setFormatter(
    logging.Formatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s")
)


def _has_config(logger):
    """Decide if a logger has direct configuration applied by checking
    its properties against the defaults.

    :param logger: The :class:`~logging.Logger` to inspect.
    """
    return (
        logger.level != logging.NOTSET
        or logger.handlers
        or logger.filters
        or not logger.propagate
    )


def create_logger(app):
    """Get the the Flask apps's logger and configure it if needed.

    The logger name will be the same as
    :attr:`app.import_name <flask.Flask.name>`.

    When :attr:`~flask.Flask.debug` is enabled, set the logger level to
    :data:`logging.DEBUG` if it is not set.

    If there is no handler for the logger's effective level, add a
    :class:`~logging.StreamHandler` for
    :func:`~flask.logging.wsgi_errors_stream` with a basic format.
    """
    logger = logging.getLogger(app.name)

    # 1.1.0 changes name of logger, warn if config is detected for old
    # name and not new name
    for old_name in ("flask.app", "flask"):
        old_logger = logging.getLogger(old_name)

        if _has_config(old_logger) and not _has_config(logger):
            warnings.warn(
                "'app.logger' is named '{name}' for this application,"
                " but configuration was found for '{old_name}', which"
                " no longer has an effect. The logging configuration"
                " should be moved to '{name}'.".format(name=app.name, old_name=old_name)
            )
            break

    if app.debug and not logger.level:
        logger.setLevel(logging.DEBUG)

    if not has_level_handler(logger):
        logger.addHandler(default_handler)

    return logger