django に Sentry を導入してログを確認してみる

django のデバッグモードだとコンソールにログが出力されますが、本番環境は特段何も設定しないとログが確認出来ません。
探してみたら無料のエラー監視ツール Sentry と言うものがあったので使って見ました。

参考

導入

基本的に本家のサイトで登録したら全て案内してくれるのでハマりどころはありませんが。

プラットフォームから django を検索すると下記のようなコードがあり settings.py に貼り付けると案内があるので貼り付けます。

import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration

sentry_sdk.init(
    dsn="https://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx@xxxxxxxx.ingest.sentry.io/0000000",
    integrations=[DjangoIntegration()],

    # Set traces_sample_rate to 1.0 to capture 100%
    # of transactions for performance monitoring.
    # We recommend adjusting this value in production.
    traces_sample_rate=1.0,

    # If you wish to associate users to errors (assuming you are using
    # django.contrib.auth) you may enable sending PII data.
    send_default_pii=True
)

これも案内がありますが SDK をインストールします。

pip install --upgrade sentry-sdk

確認

前述のコードと共にエラーを出すサンプルまで案内してくれているのでそれを urls.py に貼り付けます。

from django.urls import path

def trigger_error(request):
    division_by_zero = 1 / 0

urlpatterns = [
    path('sentry-debug/', trigger_error),
    # ...
]

ZeroDivisionError と無事該当のエラーログが確認できました。

YouTube