0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Djangoでエラーメールを送信する

Last updated at Posted at 2024-08-27

概要

Djangoでエラーメールを送信する場合は、Django提供のAdminEmailHandlerを使う。ただし利用するうえで注意点があるので、これを記載する。

  • 500エラーの際に、エラーメールが2通飛んでしまう
  • settingsの情報がすべて飛んでしまう。(本来はパスワードなどの機密情報は別で管理すべきであるが、プロジェクトによっては記載している場合もあるはず)

そこでこれらを解決すべく、AdminEmailHandlerを継承したクラスを作成してこれを利用する。

CustomEmailHandler

messageから不要な情報を削除したものを送るようにカスタマイズする。

logs.py
import re
from django.utils.log import AdminEmailHandler
from django.core import mail
class CustomEmailHandler(AdminEmailHandler):
    def send_mail(self, subject, message, *args, **kwargs):
        if not "HTTP/" in subject:
            message = re.sub(r'(COOKIES:|Settings:)[\s\S]*', '', message)
            message = re.sub(r'Django Version:[\s\S]*?Installed Middleware:[\s\S]*?\]', '', message)
            message = re.sub(r'Traceback \(most recent call last\):\n[\s]*?None', '', message)
            message = re.sub(r'(\n){3,}', '\n\n', message)
            mail.mail_admins(subject, message, connection=self.connection(), fail_silently=True, html_message=None) 

以下、settingsの必要な箇所のみ抜粋。

settings.py
LOGGING = {
    "filters": {

        "require_debug_false": {
            "()": "django.utils.log.RequireDebugFalse",
        },
        "require_debug_true": {
            "()": "django.utils.log.RequireDebugTrue",
        },
    },
    # ハンドラ
    "handlers": {
        
        "mail_admins": {
            "level": "ERROR",
            "filters": ["require_debug_true"],
            "class": "common.utils.logs.CustomEmailHandler",
        },
    },
    "loggers": {

        "": {
            "handlers": ["file", "console", "mail_admins"],
            "level": "DEBUG",
            "propagate": False,
        },

        "django": {
            "handlers": ["file", "mail_admins"],
            "level": "INFO",
            "propagate": False,
        },
    },
} 

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?