---
title: "ロギング"
version: 4.0
locale: ja
source: https://docs.djangoproject.com/ja/4.0/ref/logging/
canonical: https://djangodocs.dev/ja/4.0/ref/logging/
---
# ロギング

> **See also**
>
> - [How to configure and use logging](/ja/4.0/howto/logging/#logging-how-to)
> - [Django logging overview](/ja/4.0/topics/logging/#logging-explanation)

Django's logging module extends Python's builtin [`logging`](https://docs.python.org/3/library/logging.html#module-logging).

Logging is configured as part of the general Django [`django.setup()`](/ja/4.0/ref/applications/#django.setup)
function, so it's always available unless explicitly disabled.

## Django のデフォルトのロギング設定

By default, Django uses Python's [logging.config.dictConfig format](https://docs.python.org/3/library/logging.config.html#logging-config-dictschema).

### Default logging conditions

The full set of default logging conditions are:

[`DEBUG`](/ja/4.0/ref/settings/#std-setting-DEBUG) が `True` のとき:

- `django` ロガーは、`django` ヒエラルキー (`django.server` を除く) において、`INFO` レベル以上のメッセージをコンソールに送信します。

[`DEBUG`](/ja/4.0/ref/settings/#std-setting-DEBUG) が `False` のとき:

- `django` ロガーは、`django` ヒエラルキー (`django.server` を除く) において、`ERROR` ないし `CRITICAL` レベルを [`AdminEmailHandler`](#django.utils.log.AdminEmailHandler) に送信します。

Independently of the value of [`DEBUG`](/ja/4.0/ref/settings/#std-setting-DEBUG):

- [django.server](#django-server-logger) ロガーは `INFO` レベル以上のメッセージをコンソールに送信します。

All loggers except [django.server](#django-server-logger) 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 definition

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](https://github.com/django/django/blob/stable/4.0.x/django/utils/log.py):

```
{
    '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 [ロギングを設定する](/ja/4.0/topics/logging/#configuring-logging) on how to complement or replace this default
logging configuration.

## Django logging extensions

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

### ロガー

Django provides several built-in loggers.

#### `django`

The parent logger for messages in the `django` [named logger hierarchy](/ja/4.0/howto/logging/#naming-loggers-hierarchy). Django does not post messages using this name.
Instead, it uses one of the loggers below.

#### `django.request`

リクエストに関するログをハンドリングします。5XXレスポンスは `ERROR` メッセージとして送られ、 4XXレスポンスは `WARNING` メッセージとして送られます。 `django.security` ロガーに出力されたメッセージは、 `django.request` ロガーには送られません。

このロガーに送られるメッセージには、以下のようなコンテキストが含まれます。

- `status_code`: リクエストに対するレスポンスのHTTPレスポンスコード。
- `request`: ログのメッセージに対応するリクエストのオブジェクト。

#### `django.server`

[`runserver`](/ja/4.0/ref/django-admin/#django-admin-runserver) コマンドによって立ち上がったサーバーが受け取ったリクエストに関するログメッセージ。HTTP の 5XX レスポンスは `ERROR` メッセージとして送られ、 4XX レスポンスは `WARNING` メッセージとして送られ、その他は `INFO` メッセージとして送られます。

このロガーに送られるメッセージには、以下のようなコンテキストが含まれます。

- `status_code`: リクエストに対するレスポンスのHTTPレスポンスコード。
- `request`: ログのメッセージに対応するリクエストのオブジェクト。

#### `django.template`

テンプレートのレンダリングに関するログメッセージ。

- コンテキストに変数が無い場合は DEBUG メッセージとして送られる。

#### `django.db.backends`

コードとデータベースの間でのやりとりに関するメッセージ。例えば、アプリケーションから実行全ての SQL は `DEBUG` レベルでメッセージが送られます。

このロガーに送られるメッセージには、以下のようなコンテキストが含まれます。

- `duration`: SQLを実行するのにかかった時間。
- `sql`: 実行されたSQL文。
- `params`: SQLの呼び出しに使ったパラメータ。
- `alias`: The alias of the database used in the SQL call.

パフォーマンスの観点から、 SQL ログは、ログレベルやハンドラに関わらず、 `settings.DEBUG` に True が設定されているときのみ有効になります。

このログには、フレームワークによる初期化（例: `SET TIMEZONE` ）や、トランザクション管理のクエリ（例: `BEGIN`, `BOMMIT`, `ROLLBACK`）は含まれません。全てのデータベースクエリを見たい場合は、データベースのクエリログを有効にしてください。

> **Changed in Django 4.0**
>
> The database `alias` was added to log messages.

#### `django.security.*`

The security loggers will receive messages on any occurrence of
[`SuspiciousOperation`](/ja/4.0/ref/exceptions/#django.core.exceptions.SuspiciousOperation) and other security-related
errors. There is a sub-logger for each subtype of security error, including all
`SuspiciousOperation`s. 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`](/ja/4.0/ref/settings/#std-setting-ALLOWED_HOSTS), Django will return a 400
response, and an error message will be logged to the
`django.security.DisallowedHost` logger.

These log events will reach the `django` logger by default, which mails error
events to admins when `DEBUG=False`. Requests resulting in a 400 response due
to a `SuspiciousOperation` will not be logged to the `django.request`
logger, but only to the `django.security` logger.

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

```
'handlers': {
    'null': {
        'class': 'logging.NullHandler',
    },
},
'loggers': {
    'django.security.DisallowedHost': {
        'handlers': ['null'],
        'propagate': False,
    },
},
```

Other `django.security` loggers not based on `SuspiciousOperation` are:

- `django.security.csrf`: For [CSRF failures](/ja/4.0/ref/csrf/#csrf-rejected-requests).

#### `django.db.backends.schema`

Logs the SQL queries that are executed during schema changes to the database by
the [migrations framework](/ja/4.0/topics/migrations/). Note that it won't log the
queries executed by [`RunPython`](/ja/4.0/ref/migration-operations/#django.db.migrations.operations.RunPython).
Messages to this logger have `params` and `sql` in their extra context (but
unlike `django.db.backends`, not duration). The values have the same meaning
as explained in [django.db.backends](#django-db-logger).

### ハンドラ

Django provides one log handler in addition to [`those provided by the
Python logging module`](https://docs.python.org/3/library/logging.handlers.html#module-logging.handlers).

#### `class AdminEmailHandler(include_html=False, email_backend=None, reporter_class=None)`

This handler sends an email to the site [`ADMINS`](/ja/4.0/ref/settings/#std-setting-ADMINS) for each log
message it receives.

If the log record contains a `request` attribute, the full details
of the request will be included in the email. The email subject will
include the phrase "internal IP" if the client's IP address is in the
[`INTERNAL_IPS`](/ja/4.0/ref/settings/#std-setting-INTERNAL_IPS) setting; if not, it will include "EXTERNAL IP".

If the log record contains stack trace information, that stack
trace will be included in the 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`](/ja/4.0/ref/settings/#std-setting-DEBUG) were `True`. To set this value in your
configuration, include it in the handler definition for
`django.utils.log.AdminEmailHandler`, like this:

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

Be aware of the [security implications of logging](/ja/4.0/topics/logging/#logging-security-implications) when using the `AdminEmailHandler`.

By setting the `email_backend` argument of `AdminEmailHandler`, the
[email backend](/ja/4.0/topics/email/#topic-email-backends) that is being used by the
handler can be overridden, like this:

```
'handlers': {
    'mail_admins': {
        'level': 'ERROR',
        'class': 'django.utils.log.AdminEmailHandler',
        'email_backend': 'django.core.mail.backends.filebased.EmailBackend',
    },
},
```

By default, an instance of the email backend specified in
[`EMAIL_BACKEND`](/ja/4.0/ref/settings/#std-setting-EMAIL_BACKEND) will be used.

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:

```
'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)`

Sends emails to admin users. To customize this behavior, you can
subclass the [`AdminEmailHandler`](#django.utils.log.AdminEmailHandler) class and
override this method.

### フィルター

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

#### `class CallbackFilter(callback)`

This filter accepts a callback function (which should accept a single
argument, the record to be logged), and calls it for each record that
passes through the filter. Handling of that record will not proceed if the
callback returns False.

For instance, to filter out [`UnreadablePostError`](/ja/4.0/ref/exceptions/#django.http.UnreadablePostError)
(raised when a user cancels an upload) from the admin emails, you would
create a filter function:

```
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:

```
'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 RequireDebugFalse`

This filter will only pass on records when settings.DEBUG is False.

This filter is used as follows in the default [`LOGGING`](/ja/4.0/ref/settings/#std-setting-LOGGING)
configuration to ensure that the [`AdminEmailHandler`](#django.utils.log.AdminEmailHandler) only sends
error emails to admins when [`DEBUG`](/ja/4.0/ref/settings/#std-setting-DEBUG) is `False`:

```
'filters': {
    'require_debug_false': {
        '()': 'django.utils.log.RequireDebugFalse',
    },
},
'handlers': {
    'mail_admins': {
        'level': 'ERROR',
        'filters': ['require_debug_false'],
        'class': 'django.utils.log.AdminEmailHandler',
    },
},
```

#### `class RequireDebugTrue`

This filter is similar to [`RequireDebugFalse`](#django.utils.log.RequireDebugFalse), except that records are
passed only when [`DEBUG`](/ja/4.0/ref/settings/#std-setting-DEBUG) is `True`.
