Send email with Python logging

Question:

I’d like to send an email everytime Logger.fatal or Logger.warn is invoked.

Perhaps a solution could be to extend it and override the methods. But when you import logging, the only way to get a Logger class is using logging.getLogger().

How do I solve this?

Asked By: Jekk

||

Answers:

It’s not a best solution to override logger methods.

Python logging configuration supports multiple loggers which then support multiple handlers (files, stdout, email). Handlers in turn have different formatters (string format how log entry is displayed), but it’s offtopic for this question.

In fact Python supports email logging out of the box through SMTPHandler.

Because you did not include details about your application and logger setup it is not possible to give answer specific to your question. But generally outline is this

  • Add a SMTPHandler handler root logger (call logging.getLogger() with arguments should give you the root lgoger)

  • Make the handler level WARN so that it ignores INFO, and DEBUG levels

See also proper mechanism to initialize loggers in your Python code.

Answered By: Mikko Ohtamaa

I have also created an EmailHandler to Red Mail to make things easy for people.

It works like this:

import logging
from redmail import EmailHandler

# Create the email handler
hdlr = EmailHandler(
    host="localhost",
    port=0,
    username="[email protected]",
    password="<PASSWORD>",

    subject="Log Record: {record.levelname}",
    receivers=["[email protected]"],
    text="""
        Logging level: {{ record.levelname }}
        Message: {{ msg }}
    """,
    html="""
        <ul>
            <li>Logging level: {{ record.levelname }}</li>
            <li>Message: {{ msg }}</li>
        </ul>
    """,
)

# Add the handler
logger = logging.getLogger("mylogger")
logger.addHandler(hdlr)

It uses Jinja for templating for the bodies (that’s why we used but regular string formatting for the subject. You can also use only text or just the subject if you wish to have simpler emails.

Then to use this, just log away:

logger.warning("Watch out!")

There is also a MultiEmailHandler that sends multiple log records at once if you wish to avoid flooding your inbox with log messages.

Install

It’s on PyPI so you can install it with:

pip install redmail

Relevant links:

Answered By: miksus
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.