Send Python logs to Teams

When any error occurs in your application, by sending error notifications to Teams (or Slack, etc.), you can know what happened and deal with the problem immediately.

In Python, this can be achieved by implementing a custom logging handler:

import logging
import socket

import requests


class TeamsNofityHandler(logging.Handler):
    def __init__(self, webhook_url, service_name, **kwargs):
        self.service_name = service_name
        self.webhook_url = webhook_url
        logging.Handler.__init__(self)

    @property
    def hostname(self):
        return socket.gethostname()

    def emit(self, record):
        level = record.levelname
        msg = record.getMessage()
        if record.levelno > 30:
            # events that log level above WARNING
            msg_full = self.format(record)
            payload = self.build_payload(level, msg, True, msg_full)
        else:
            payload = self.build_payload(level, msg)
        self.send_notification(payload)

    def build_payload(self, level, msg, verbose=False, msg_full=None):
        title = f'📢 An error occurred in {self.service_name}'
        payload = {
            'themeColor': 'ffc986' if level == 'WARNING' else 'ff4e4e',
            'summary': title,
            'sections': [{
                'activityTitle': title,
                'facts': [{
                    'name': 'Level',
                    'value': level
                }, {
                    'name': 'Hostname',
                    'value': self.hostname
                }, {
                    'name': 'Message',
                    'value': msg
                }],
                'markdown': True
            }]
        }
        if verbose:
            payload['sections'][0]['text'] = f'`{msg_full}`'
        return payload

    def send_notification(self, payload):
        r = requests.post(
            url=self.webhook_url,
            headers={'Content-Type': 'application/json'},
            json=payload
        )
        return r.status_code

In order to send messages to Teams, you first have to create an incoming webhook.

After creating, you will get a unique URL, then you can use this URL to post messages.

The above example can be used like this:

teams_handler = TeamsNofityHandler(WEBHOOK_URL, SERVICE_NAME)
logger = logging.getLogger()
logger.setLevel(logging.WARNING)
logger.addHandler(teams_handler)

logger.error('msg')

Tags:

Updated: