ロギング¶
クイックロギング入門¶
Djangoはロギングのために、Pythonビルトインの logging
モジュールを使用しています。このモジュールの使い方はPythonのドキュメントに記述されています。しかし、もしあなたがPythonのロギングフレームワークを使ったことがない場合(もしくはある場合も)、これは素早い入門になるでしょう。
登場人物¶
Pythonのロギングは4つの部分で構成されます。
ロガー¶
ロガーはロギングシステムのエントリーポイントです。各ロガーは処理が記述されたメッセージの名前付けされたバケツです。
ロガーには ログレベル が設定されています。このログレベルはハンドリングされたログメッセージの深刻さを表しています。Pythonは下記のログレベルを定義しています。
DEBUG
: デバッグのための低レベルシステム情報INFO
: 一般的なシステム情報WARNING
: 重要度の小さい問題が発生したことを示す情報ERROR
: 大きな問題が発生したことを示す情報CRITICAL
: 重大な問題が発生したことを示す情報
ロガーに記載された各メッセージは ログレコード です。各ログレコードは、特定のメッセージの重要性を表す ログレベル を持ちます。ログレコードには、記録されたイベントを説明するメタデータを含むことができます。これには、スタックトレースやエラーコードと言った詳細を含めることができます。
ロガーにメッセージが渡されたとき、メッセージのログレベルはロガーのログレベルと比較されます。メッセージのログレベルがロガー自体のログレベルと同等以上の場合、メッセージは次の処理に進みます。それ以外の場合、メッセージは無視されます。
ロガーによってメッセージの処理が必要だと判断された場合、メッセージは ハンドラ に渡されます。
ハンドラ¶
ハンドラは、ロガー上で書くメッセージに何をするかを決定するための原動力です。ここで、メッセージを表示する、ファイルに書き込む、ネットワークソケットに送信する、といった特定のロギング動作を記述します。
ロガーと同様に、ハンドラもログレベルを持ちます。ログレコードのログレベルがハンドラのレベルに満たない場合、ハンドラはメッセージを無視します。
ロガーには複数のハンドラを設定でき、また各ハンドラは異なるログレベルを持つことができます。この方法により、メッセージの重要性に応じて通知方法を変えることができます。たとえば、ERROR
と CRITICAL
メッセージを呼び出しサービスに転送するハンドラを設定する一方で、後で分析するために (ERROR
や``CRITICAL`` も含む) すべてのメッセージをファイルに記録する 2 つめのハンドラをセットすることができます。
フィルタ¶
フィルターは、どのログレコードがロガーからハンドラへ渡されるかについて、追加的なコントロールを提供します。
デフォルトでは、ログレベル要件を満たしたすべてのログメッセージが処理されます。しかし、フィルタを使用することで、ロギングのプロセスに追加的な要件を設定できます。たとえば、特定のソースからの ERROR
のみを処理するようにフィルタを設定することができます。
フィルタは、処理前にログレコードを修正するためにも使えます。たとえば、特定の条件を満たした場合に ERROR
ログレコードを WARNING
レコードに格下げさせるようなフィルタを設定できます。
フィルタは、ロガーもしくはハンドラに対して設定できます; 複数のフィルタを使って複数のフィルタ動作を連鎖させることも可能です。
フォーマッタ¶
最終的には、ログレコードはテキストとして表現される必要があります。フォーマッタはこのテキストの書式を定義します。フォーマッタは、通常は Python の文字列フォーマットで、LogRecord 属性 を含みます; しかし、特定の書式設定を行うような独自のフォーマッタを記述することもできます。
ロギングを使用する¶
ロガー、ハンドラ、フィルタ、フォーマッタを設定し終えたら、コード内にロギングの呼び出しを設置する必要があります。ロギングのフレームワークの使用は非常にシンプルです。例をご覧ください:
# import the logging library
import logging
# Get an instance of a logger
logger = logging.getLogger(__name__)
def my_view(request, arg1, arg):
...
if bad_mojo:
# Log an error message
logger.error('Something went wrong!')
そう、これだけです! bad_mojo
の状態がアクティブなときは、毎回エラーログが記述されます。
ロガーに名前をつける¶
logging.getLogger()
を呼ぶと、(必要であればロガーを作成したうえで)ロガーのインスタンスを取得します。このロガーのインスタンスは名前によって区別されます。名前は、ロガーの設定を、目的に応じて区別するために利用します。
慣習として、logger の名前は通常 __name__
とし、logger が含まれている Python モジュールの名前となるようにします。これにより、ロギングの呼び出しをモジュールごとにフィルタ・ハンドリングできるようになります。しかし、ロギングメッセージを他の方法で組織したい場合は、ドット区切りの名前を logger に与えることもできます。
# Get an instance of a specific named logger
logger = logging.getLogger('project.interesting.stuff')
ロガーの名前がドットで区切られているのは、階層関係を表しています。project.interesting
という名前のロガーは、project.interesting.stuff
という名前のロガーの親になります。project
という名前のロガーは、project.interesting
の親になります。
この階層関係は重要です。ログの呼び出しは、親のロガーに伝播します。ルートのロガーにのみハンドラをセットして、子のロガーの呼び出しを全てこのハンドラでキャッチするということができます。project
という名前のロガーは project.interesting
や project.interesting.stuff
ロガーのログも全てキャッチできます。
伝播の設定はロガーごとに設定できます。親のロガーに伝播させたくない場合は、伝播しないように設定することもできます。
ロギング呼び出しを作成する¶
ロガーのインスタンスは、デフォルトの各ログレベルに対する入力方法を含んでいます:
logger.debug()
logger.info()
logger.warning()
logger.error()
logger.critical()
さらに 2 つのロギング呼び出しが可能です:
logger.log()
: 手動で、特定のログレベルでロギングメッセージを吐き出します。logger.exception()
: 例外のスタックトレースをラップした、ERRORレベルのログメッセージを生成します。
ロギングを設定する¶
もちろん、コード内にロギング呼び出しを設置するだけでは不十分です。ロガー、ハンドラ、フィルタおよびフォーマッタが、役立つ形でロギング出力をするように設定する必要があります。
Python のロギングライブラリは、実用的なインターフェースから設定ファイルまで、ロギング設定のテクニックを提供しています。デフォルトでは、Django は dictConfig フォーマット を使用します。
In order to configure logging, you use LOGGING
to define a
dictionary of logging settings. These settings describe the loggers,
handlers, filters and formatters that you want in your logging setup,
and the log levels and other properties that you want those components
to have.
デフォルトでは、LOGGING
設定は、以下のスキームを使って Django のデフォルトロギング設定 に統合されています。
LOGGING
の disable_existing_loggers
キーの値を True
にすると、全てのデフォルトの設定が無効になります(キーが存在しない場合は dictConfig
のデフォルトになります)。このため、 'disable_existing_loggers': True
を使う場合は注意してください。 True
を設定する必要は殆どないでしょう。 disable_existing_loggers
を False
に設定して、デフォルトのロガーの一部、または全てを定義しなおすこともできます。あるいは、 LOGGING_CONFIG
を None
に設定して、 ロギングの設定を自分で行うこと も出来ます。
ロギングは、一般的な Django の setup()
関数の一部として設定されます。したがって、ロガーが常にプロジェクトコード内で使用準備ができていることが保証されています。
例¶
dictConfig フォーマット に関する完全なドキュメントが、ロギング設定ディクショナリの最高の教材です。とはいえ、どんなことが可能なのか知ってもらうため、以下にいくつかの例を示します。
最初に、全てのログメッセージをコンソールに出力するための最低限の設定がこちらです。
import os
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'root': {
'handlers': ['console'],
'level': 'WARNING',
},
}
この設定では、 root
という名前の親のロガーがあり、 WARNING
レベル以上のメッセージを受け取ったら、 console ハンドラに送るようになっています。 level を INFO
または DEBUG
にすると、より詳細なメッセージも表示されるようになります。この設定は開発中に役に立ちます。
Next we can add more fine-grained logging. Here's an example of how to make the logging system print more messages from just the django named logger:
import os
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'root': {
'handlers': ['console'],
'level': 'WARNING',
},
'loggers': {
'django': {
'handlers': ['console'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
'propagate': False,
},
},
}
By default, this config sends messages from the django
logger of level
INFO
or higher to the console. This is the same level as Django's default
logging config, except that the default config only displays log records when
DEBUG=True
. Django does not log many such INFO
level messages. With
this config, however, you can also set the environment variable
DJANGO_LOG_LEVEL=DEBUG
to see all of Django's debug logging which is very
verbose as it includes all database queries.
必ずしもコンソールに出力する必要はありません。 django という名前のロガーをファイルに書き込むにはこのように設定します。
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': '/path/to/django/debug.log',
},
},
'loggers': {
'django': {
'handlers': ['file'],
'level': 'DEBUG',
'propagate': True,
},
},
}
この例を使用するときは、'filename'
のパスを Django アプリケーションを実行しているユーザーが書き込み可能な場所に変更してください。
最後に、かなり複雑なロギングの設定の例です。
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}',
'style': '{',
},
'simple': {
'format': '{levelname} {message}',
'style': '{',
},
},
'filters': {
'special': {
'()': 'project.logging.SpecialFilter',
'foo': 'bar',
},
'require_debug_true': {
'()': 'django.utils.log.RequireDebugTrue',
},
},
'handlers': {
'console': {
'level': 'INFO',
'filters': ['require_debug_true'],
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler',
'filters': ['special']
}
},
'loggers': {
'django': {
'handlers': ['console'],
'propagate': True,
},
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': False,
},
'myproject.custom': {
'handlers': ['console', 'mail_admins'],
'level': 'INFO',
'filters': ['special']
}
}
}
このロギング設定は、以下のことを行います:
設定が「dictConfig バージョン 1」形式であることを明示します。 現在、これが唯一の dictConfig 形式のバージョンです。
2 つのフォーマッタを定義します:
simple
, that outputs the log level name (e.g.,DEBUG
) and the log message.この
format
文字列は標準の Python 文字列フォーマットで、各ログ行で出力される詳細を定義します。出力可能な詳細の全リストは Formatter Objects に記載されています。verbose
は、ログレベルの名称とログメッセージに加えて、時刻、プロセス、スレッド、ログメッセージを生成したモジュールを出力します。
2 つのフィルタを定義します:
project.logging.SpecialFilter
, using the aliasspecial
. If this filter required additional arguments, they can be provided as additional keys in the filter configuration dictionary. In this case, the argumentfoo
will be given a value ofbar
when instantiatingSpecialFilter
.django.utils.log.RequireDebugTrue
は、DEBUG
がTrue
のときにレコードの処理を進めます。
2 つのハンドラを定義します:
console
は、すべてのINFO
以上のメッセージをsys.stderr
に表示 (print) するStreamHandler
クラスです。このハンドラはsimple
出力フォーマットを使用します。mail_admins` は、すべての ``ERROR
以上のメッセージをADMINS
に E メール送信するAdminEmailHandler
です。このハンドラはspecial
フィルタを使用します。
3 つのロガーを設定します:
django
は、すべてのメッセージをconsole
ハンドラに渡します。django.request
は、すべてのERROR
メッセージをmail_admins
ハンドラに渡します。加えて、このロガーはメッセージを親に 伝えない よう設定されています。これは、django.request
内に記述されたログメッセージはdjango
ロガーで処理されないことを意味します。myproject.custom
はINFO
もしくはそれ以上のすべてのメッセージを渡し、special
フィルタを 2 つのハンドラに引き渡します --console
とmail_admins
です。これは、INFO
以上のレベルのメッセージがコンソールで表示され、さらにERROR
とCRITICAL
のメッセージは E メールでも出力されることを意味します。
カスタムのロギング設定¶
ロガーの設定に Python の dictConfig フォーマットを使用したくない場合は、あなた自身の設定スキームを定義することができます。
The LOGGING_CONFIG
setting defines the callable that will
be used to configure Django's loggers. By default, it points at
Python's logging.config.dictConfig()
function. However, if you want to
use a different configuration process, you can use any other callable
that takes a single argument. The contents of LOGGING
will
be provided as the value of that argument when logging is configured.
ロギング設定を無効化する¶
ロギングを全く設定したくない(あるいは、自分でロギングをやりたい)なら、 LOGGING_CONFIG
を None
に設定することもできます。これにより、 Django のデフォルトのロギング設定 を無効化できます。
LOGGING_CONFIG
を None
に設定すると、自動でロギングの設定が行われなくなるだけです。ロギング自体が使えなくなるわけではありません。自動でのロギング設定を無効化しても、 Django はロギングのメソッドを呼び、もしログ設定がされていれば、そこに出力されます。
Django の自動でのログ設定を無効化し、手動で設定する場合はこのようにします。
LOGGING_CONFIG = None
import logging.config
logging.config.dictConfig(...)
Note that the default configuration process only calls
LOGGING_CONFIG
once settings are fully-loaded. In contrast, manually
configuring the logging in your settings file will load your logging config
immediately. As such, your logging config must appear after any settings on
which it depends.
Django's logging extensions¶
Django は、Webサーバーで特有のログに関する便利な機能を提供しています。
ロガー¶
Django provides several built-in loggers.
django
¶
django
ヒエラルキーにある全てのメッセージをキャッチするロガーです。 django という名前で送られるメッセージはありませんが、以下の名前のロガーからメッセージが送られてきます。
django.request
¶
リクエストに関するログをハンドリングします。5XXレスポンスは ERROR
メッセージとして送られ、 4XXレスポンスは WARNING
メッセージとして送られます。 django.security
ロガーに出力されたメッセージは、 django.request
ロガーには送られません。
このロガーに送られるメッセージには、以下のようなコンテキストが含まれます。
status_code
: リクエストに対するレスポンスのHTTPレスポンスコード。request
: ログのメッセージに対応するリクエストのオブジェクト。
django.server
¶
runserver
コマンドによって立ち上がったサーバーが受け取ったリクエストに関するログメッセージ。HTTP の 5XX レスポンスは ERROR
メッセージとして送られ、 4XX レスポンスは WARNING
メッセージとして送られ、その他は INFO
メッセージとして送られます。
このロガーに送られるメッセージには、以下のようなコンテキストが含まれます。
status_code
: リクエストに対するレスポンスのHTTPレスポンスコード。request
: ログのメッセージに対応するリクエストのオブジェクト。
django.db.backends
¶
コードとデータベースの間でのやりとりに関するメッセージ。例えば、アプリケーションから実行全ての SQL は DEBUG
レベルでメッセージが送られます。
このロガーに送られるメッセージには、以下のようなコンテキストが含まれます。
duration
: SQLを実行するのにかかった時間。sql
: 実行されたSQL文。params
: SQLの呼び出しに使ったパラメータ。
パフォーマンスの観点から、 SQL ログは、ログレベルやハンドラに関わらず、 settings.DEBUG
に True が設定されているときのみ有効になります。
このログには、フレームワークによる初期化(例: SET TIMEZONE
)や、トランザクション管理のクエリ(例: BEGIN
, BOMMIT
, ROLLBACK
)は含まれません。全てのデータベースクエリを見たい場合は、データベースのクエリログを有効にしてください。
django.security.*
¶
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
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
, 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.
django.db.backends.schema
¶
Logs the SQL queries that are executed during schema changes to the database by
the migrations framework. Note that it won't log the
queries executed by 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 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)¶ This handler sends an email to the site
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 theINTERNAL_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 ofAdminEmailHandler
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 ifDEBUG
wereTrue
. To set this value in your configuration, include it in the handler definition fordjango.utils.log.AdminEmailHandler
, like this:'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'include_html': True, } },
Note that this HTML version of the email contains a full traceback, with names and values of local variables at each level of the stack, plus the values of your Django settings. This information is potentially very sensitive, and you may not want to send it over email. Consider using something such as Sentry to get the best of both worlds -- the rich information of full tracebacks plus the security of not sending the information over email. You may also explicitly designate certain sensitive information to be filtered out of error reports -- learn more on Filtering error reports.
By setting the
email_backend
argument ofAdminEmailHandler
, the email backend 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
will be used.The
reporter_class
argument ofAdminEmailHandler
allows providing andjango.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
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
(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
configuration to ensure that theAdminEmailHandler
only sends error emails to admins whenDEBUG
isFalse
:'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
, except that records are passed only whenDEBUG
isTrue
.
Django のデフォルトのロギング設定¶
デフォルトでは、Django は以下のロギングを設定してあります:
DEBUG
が True
のとき:
django
ロガーは、django
ヒエラルキー (django.server
を除く) において、INFO
レベル以上のメッセージをコンソールに送信します。
DEBUG
が False
のとき:
django
ロガーは、django
ヒエラルキー (django.server
を除く) において、ERROR
ないしCRITICAL
レベルをAdminEmailHandler
に送信します。
DEBUG
の値にかかわらず:
- django.server ロガーは
INFO
レベル以上のメッセージをコンソールに送信します。
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.
django/utils/log.py で定義されている、このデフォルト設定を補完または置換する方法を知りたい場合は、ロギングを設定する を参照してください。