LoggingLink para este cabeçalho

Django’s logging module extends Python’s builtin logging.

Logging is configured as part of the general Django django.setup() function, so it’s always available unless explicitly disabled.

A configuração default de log do DjangoLink para este cabeçalho

By default, Django uses Python’s logging.config.dictConfig format.

Default logging conditionsLink para este cabeçalho

The full set of default logging conditions are:

Quando DEBUG é True:

  • The django logger sends messages in the django hierarchy (except django.server) at the INFO level or higher to the console.

Quando DEBUG é False:

  • The django logger sends messages in the django hierarchy (except django.server) with ERROR or CRITICAL level to AdminEmailHandler.

Independently of the value of DEBUG:

  • The django.server logger sends messages at the INFO level or higher to the console.

All loggers except django.server propagate logging to their parents, up to the root django logger. The console and mail_admins handlers are attached to the root logger to provide the behavior described above.

Python’s own defaults send records of level WARNING and higher to the console.

Default logging definitionLink para este cabeçalho

Django’s default logging configuration inherits Python’s defaults. It’s available as django.utils.log.DEFAULT_LOGGING and defined in django/utils/log.py:

Code
{
    "version": 1,
    "disable_existing_loggers": False,
    "filters": {
        "require_debug_false": {
            "()": "django.utils.log.RequireDebugFalse",
        },
        "require_debug_true": {
            "()": "django.utils.log.RequireDebugTrue",
        },
    },
    "formatters": {
        "django.server": {
            "()": "django.utils.log.ServerFormatter",
            "format": "[{server_time}] {message}",
            "style": "{",
        }
    },
    "handlers": {
        "console": {
            "level": "INFO",
            "filters": ["require_debug_true"],
            "class": "logging.StreamHandler",
        },
        "django.server": {
            "level": "INFO",
            "class": "logging.StreamHandler",
            "formatter": "django.server",
        },
        "mail_admins": {
            "level": "ERROR",
            "filters": ["require_debug_false"],
            "class": "django.utils.log.AdminEmailHandler",
        },
    },
    "loggers": {
        "django": {
            "handlers": ["console", "mail_admins"],
            "level": "INFO",
        },
        "django.server": {
            "handlers": ["django.server"],
            "level": "INFO",
            "propagate": False,
        },
    },
}

See Configuring logging on how to complement or replace this default logging configuration.

Django logging extensionsLink para este cabeçalho

Django provides a number of utilities to handle the particular requirements of logging in a web server environment.

LoggersLink para este cabeçalho

O Django fornece vários loggers embutidos.

djangoLink para este cabeçalho

The parent logger for messages in the django named logger hierarchy. Django does not post messages using this name. Instead, it uses one of the loggers below.

django.requestLink para este cabeçalho

Log messages related to the handling of requests. 5XX responses are raised as ERROR messages; 4XX responses are raised as WARNING messages. Requests that are logged to the django.security logger aren’t logged to django.request.

Mensagens para esse logger possuem o seguinte contexto adicional:

  • status_code: o código da resposta HTTP associado a requisição.

  • request: O objeto da requisição que gerou a mensagem de log.

django.serverLink para este cabeçalho

Mensagens de log relacionadas com a manipulação de requisições recebidas pelo comando runserver. Respostas HTTP 5XX são logadas como mensagens do tipo ERROR, respostas HTTP 4XX são logadas como mensagens do tipo WARNING, e todo o resto é logado como INFO.

Mensagens para esse logger possuem o seguinte contexto adicional:

  • status_code: o código da resposta HTTP associado a requisição.

  • request: The request object (a socket.socket) that generated the logging message.

django.templateLink para este cabeçalho

Mensagens de log relacionadas a renderização de templates.

  • Variáveis de contexto esquecidas são logadas como mensagens do tipo DEBUG.

django.db.backendsLink para este cabeçalho

Mensagens relacionadas a interação de código com o banco de dados. Por exemplo, cada comando SQL executado por uma requisição é logada no level DEBUG para esse logger.

Mensagens para esse logger possuem o seguinte contexto adicional:

  • duration: O tempo tomado para executar o comando SQL.

  • sql: O comando SQL que foi executado.

  • params: Os parâmetros que foram usados na chamada SQL.

  • alias: The alias of the database used in the SQL call.

Por questões de performance, o log de SQL só é ativado quando settings.DEBUG é configurado como True, independentemente do level de log ou dos handlers que estão instalados.

This logging does not include framework-level initialization (e.g. SET TIMEZONE). Turn on query logging in your database if you wish to view all database queries.

django.utils.autoreloadLink para este cabeçalho

Log messages related to automatic code reloading during the execution of the Django development server. This logger generates an INFO message upon detecting a modification in a source code file and may produce WARNING messages during filesystem inspection and event subscription processes.

django.contrib.authLink para este cabeçalho

Log messages related to django.contrib.auth, particularly ERROR messages are generated when a PasswordResetForm is successfully submitted but the password reset email cannot be delivered due to a mail sending exception.

createsuperuserLink para este cabeçalho

Log messages related to GeoDjango at various points: during the loading of external GeoSpatial libraries (GEOS, GDAL, etc.) and when reporting errors. Each ERROR log record includes the caught exception and relevant contextual data.

django.dispatchLink para este cabeçalho

This logger is used in Signals, specifically within the Signal class, to report issues when dispatching a signal to a connected receiver. The ERROR log record includes the caught exception as exc_info and adds the following extra context:

  • receiver: The name of the receiver.

  • err: The exception that occurred when calling the receiver.

django.security.*Link para este cabeçalho

The security loggers will receive messages on any occurrence of SuspiciousOperation and other security-related errors. There is a sub-logger for each subtype of security error, including all SuspiciousOperations. The level of the log event depends on where the exception is handled. Most occurrences are logged as a warning, while any SuspiciousOperation that reaches the WSGI handler will be logged as an error. For example, when an HTTP Host header is included in a request from a client that does not match ALLOWED_HOSTS, Django will return a 400 response, and an error message will be logged to the django.security.DisallowedHost logger.

Esses eventos de log irão alcançar o logger django por padrão, que irá enviar emails de eventos de erro para os administradores quando DEBUG=False. Requisições resultando em uma resposta 400 devido a uma SuspiciousOperation não serão logadas no logger django.request, mas somente para o logger django.security.

To silence a particular type of SuspiciousOperation, you can override that specific logger following this example:

Code
LOGGING = {
    # ...
    "handlers": {
        "null": {
            "class": "logging.NullHandler",
        },
    },
    "loggers": {
        "django.security.DisallowedHost": {
            "handlers": ["null"],
            "propagate": False,
        },
    },
    # ...
}

Outros loggers django.security não baseados em SuspiciousOperation são:

django.db.backends.schemaLink para este cabeçalho

Loga as consultas SQL que são executadas durante mudanças de esquema no banco de dados pelo migrations framework. Note que ele não irá logar as consultas executadas pela classe RunPython. As mensagens para esse logger possuem params e sql em seu contexto extra (mas ao contrário de django.db.backends, não possui duration). Os valores tem o mesmo significado como explicado em django.db.backends.

django.contrib.sessionsLink para este cabeçalho

Log messages related to the session framework.

ManipuladoresLink para este cabeçalho

Django provides one log handler in addition to those provided by the Python logging module.

class AdminEmailHandler(include_html=False, email_backend=None, reporter_class=None, using=None)Link para esta definição

This handler sends an email to the site ADMINS for each log message it receives.

Se o registro de log contém um atributo request, todos os detalhes da requisição serão incluídos no email. O assunto do email irá incluir a fase “internal IP” se o endereço IP do cliente foi informado em INTERNAL_IPS; Caso contrário, ele irá incluir o “EXTERNAL IP”.

Se o registro de log contiver infromações de rastreamento de pilha, o rastreamento de pilha será incluído no email.

The include_html argument of AdminEmailHandler is used to control whether the traceback email includes an HTML attachment containing the full content of the debug web page that would have been produced if DEBUG were True. To set this value in your configuration, include it in the handler definition for django.utils.log.AdminEmailHandler, like this:

Code
"handlers": {
    "mail_admins": {
        "level": "ERROR",
        "class": "django.utils.log.AdminEmailHandler",
        "include_html": True,
    },
}

Be aware of the security implications of logging when using the AdminEmailHandler.

Email is sent using the default mailer. This can be overridden by setting the using argument of AdminEmailHandler, like this:

Code
"handlers": {
    "mail_admins": {
        "level": "ERROR",
        "class": "django.utils.log.AdminEmailHandler",
        "using": "internal",
    },
}

If the specified mailer is not configured in the MAILERS setting, no email will be sent and no additional error will be raised.

By setting the deprecated email_backend argument of AdminEmailHandler, the email backend that is being used by the handler can be overridden. email_backend is not supported when MAILERS is defined or when the using argument is provided.

The reporter_class argument of AdminEmailHandler allows providing an django.views.debug.ExceptionReporter subclass to customize the traceback text sent in the email body. You provide a string import path to the class you wish to use, like this:

Code
"handlers": {
    "mail_admins": {
        "level": "ERROR",
        "class": "django.utils.log.AdminEmailHandler",
        "include_html": True,
        "reporter_class": "somepackage.error_reporter.CustomErrorReporter",
    },
}
send_mail(subject, message, *args, **kwargs)Link para esta definição

Envia emails para os usuários administradores. Para customizar esse comportamento, você pode fazer uma subclasse de AdminEmailHandler e sobrescrever esse método.

FiltrosLink para este cabeçalho

Django provides some log filters in addition to those provided by the Python logging module.

class CallbackFilter(callback)Link para esta definição

Esse filter aceita uma função de callback (que deve aceitar um único argumento, o registro a ser logado), e chama essa função para cada registro que passa pelo filter. A manipulação desse registro não será continuada caso a função de callback retorne False.

Por exemplo, para filtrar para fora exceções do tipo UnreadablePostError (levantadas quando o usuário cancela um upload) de emails destinadoas a administradores, você teria que criar uma função de filtro:

Code
from django.http import UnreadablePostError


def skip_unreadable_post(record):
    if record.exc_info:
        exc_type, exc_value = record.exc_info[:2]
        if isinstance(exc_value, UnreadablePostError):
            return False
    return True

and then add it to your logging config:

Code
LOGGING = {
    # ...
    "filters": {
        "skip_unreadable_posts": {
            "()": "django.utils.log.CallbackFilter",
            "callback": skip_unreadable_post,
        },
    },
    "handlers": {
        "mail_admins": {
            "level": "ERROR",
            "filters": ["skip_unreadable_posts"],
            "class": "django.utils.log.AdminEmailHandler",
        },
    },
    # ...
}
class RequireDebugFalseLink para esta definição

Esse filtro irá passar adiante registros de logs somente quando settings.DEBUG for False.

This filter is used as follows in the default LOGGING configuration to ensure that the AdminEmailHandler only sends error emails to admins when DEBUG is False:

Code
LOGGING = {
    # ...
    "filters": {
        "require_debug_false": {
            "()": "django.utils.log.RequireDebugFalse",
        },
    },
    "handlers": {
        "mail_admins": {
            "level": "ERROR",
            "filters": ["require_debug_false"],
            "class": "django.utils.log.AdminEmailHandler",
        },
    },
    # ...
}
class RequireDebugTrueLink para esta definição

Esse filtro é similar a RequireDebugFalse, exceto pelo fato de que os registros são passados adiante somente quando DEBUG é True.