Settting up logger to send emails to address different than admins

315 Views Asked by At

In the settings file I have a logger set up to send any errors to ADMINS which is the default behavior. Here:

LOGGING = {
  'handlers': {'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler'}
  'loggers': {'django.request': {'handlers': ['mail_admins'], 'propagate': True}}
}

But I would like to set up a second logger to log a different type of errors and email should be sent to a different address.

I have my own logging function which writes to a file. Basically I want to send an email to that other address instead. How can I do this?

1

There are 1 best solutions below

0
Albin Antony On

I don't know if it will work or not. You probably may want to override Django 'AdminEmailHandler' class.

Try overriding like this

from project import settings
from django.utils.log import AdminEmailHandler
from django.core.mail.message import  EmailMultiAlternatives

class CustomEmailHandler(AdminEmailHandler):

    def mail_extra_people(self, subject, message, fail_silently=False, connection=None,
                          html_message=None):
        """Sends a message to the extra people, as defined by the EXTRA_PEOPLE setting."""
        if not settings.EXTRA_PEOPLE:
            return
        mail = EmailMultiAlternatives(
            '%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject), message,
            settings.SERVER_EMAIL, [a[1] for a in settings.EXTRA_PEOPLE],
            connection=connection,
        )
        if html_message:
            mail.attach_alternative(html_message, 'text/html')
        mail.send(fail_silently=fail_silently)

    def send_mail(self, subject, message, *args, **kwargs):
        self.mail_extra_people(subject, message, *args, connection=self.connection(), **kwargs)

And change your logging to

LOGGING = {
    'handlers': {
        'mail_extra_people': {
            'level': 'ERROR',
            'class': 'project.myutils.CustomEmailHandler',
        },
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_extra_people'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

This should send mails to the mail ids that are mentioned in EXTRA_PEOPLE in project settings