Skip to main content
Join the official 2019 Python Developers SurveyStart the survey!

A Python logging handler for Slack integration

Project description

slack_log_utils

PyPI PyPI PyPI Build Status Say Thanks!

A Python logging handler & formatter for Slack integration.

How To Install

To install slack-log-utils, simply:

pip install slack-log-utils

or using pipenv:

pipenv install slack-log-utils

Getting Started

Get an Incoming Webhook URL on Slack.

Instantiate manually:

import logging
from slack_log_utils import SlackWebhookFormatter, SlackWebhookHandler

formatter = SlackWebhookFormatter()
handler = SlackWebhookHandler('https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX')
handler.setFormatter(formatter)
handler.setLevel(logging.WARNING)

logger = logging.getLogger('sample_log')
logger.addHandler(handler)

Instantiate using the logging.config.dictConfig method:

import logging.config
from slack_log_utils import SlackWebhookFormatter, SlackWebhookHandler

logging_config = {
    'version': 1,
    'formatters': {
        'slack': {
            '()': SlackWebhookFormatter,
        },
    },
    'handlers': {
        'slack': {
            '()': SlackWebhookHandler,
            'formatter': 'slack',
            'level': logging.WARNING,
            'url': 'https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX',
        },
    },
    'loggers': {
        'sample_log': {
            'level': logging.DEBUG,
            'handlers': ['slack'],        
        },
    },
}

logging.config.dictConfig(logging_config)
logger = logging.getLogger('sample_log')

Read more about logging configuration in the Python docs.

You can then use it just like any logger:

logger.info('This will NOT post to Slack')  # Since handler's level is set to WARNING
logger.error('This will post to Slack')

logger.error('[%s]: There are %s errors!', 'CRITICAL', 8)

Below is the logic contained within SlackWebhookFormatter on how a logging.LogRecord is formatted:

import json 

formatted_msg = super(SlackWebhookFormatter, self).format(record)

color = '#36a64f' \ 
    if record.levelno < logging.WARNING \
    else '#ff0000'

attachment = {
    'author_name': record.name,
    'title': getattr(record, 'title', ''),
    'text': formatted_msg,
    'fallback': formatted_msg,
    'color': color,
}

return json.dumps({
    'attachments': [attachment]
})

First, it uses the logging.Formatter's base format() method in order to get the %-style format string. Then, the color is decided based on the record's level. If it's less than logging.WARNING, it will be Green, else Red. The author_name is set from record.name which is the name of the logger used to log the call ('sample_log' in this case). The title is optionally set by using the key in the extra dict argument for the call to the logger:

logger.error('Sample Message Attachment!', extra={'title': 'Sample Title'})

An example of what this will look like can be seen in the Slack Message Builder.

Please see the Python LogRecord docs for the exact meaning of record.levelno, record.name, and other attrtibutes.

For further details on formatting messages, refer to the following Slack API pages:

Currently, all log messages will be sent as an attachment to Slack and it is only possible to send a single attachment at a time. Future releases may make this more configurable.

Release Notes

0.1.5 (2018-05-19)

  • Modified .travis.yml
    • Added skip_existing flag to deployments. This will stop parallel builds from failing (see here).
    • Made it so all branches will be built, but keeping that only tagged commits on master branch will be deployed to PyPI.
  • Updated README with badges from shields.io.

0.1.4 (2018-05-19)

  • Modified .travis.yml to fix issue with Travis-CI skipping deployment although the commit was tagged (see here).

0.1.3 (2018-05-19)

  • Small code style change in slack_webhook_formatter.py.

0.1.2 (2018-05-19)

  • Added .travis.yml file for Travis-CI builds.

0.1.1 (2018-05-19)

  • Bumped version for README changes to show on PyPI.

0.1.0 (2018-05-19)

  • First release on PyPI.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for slack-log-utils, version 0.1.5
Filename, size File type Python version Upload date Hashes
Filename, size slack_log_utils-0.1.5-py2.py3-none-any.whl (5.7 kB) File type Wheel Python version py2.py3 Upload date Hashes View hashes
Filename, size slack_log_utils-0.1.5.tar.gz (4.5 kB) File type Source Python version None Upload date Hashes View hashes

Supported by

Elastic Elastic Search Pingdom Pingdom Monitoring Google Google BigQuery Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN SignalFx SignalFx Supporter DigiCert DigiCert EV certificate StatusPage StatusPage Status page