Skip to main content

Direct Python log output to Discord

Project description

PyPI version

Automated test suite

Documentation Status

Python logging handler for Discord

Redirect your Python log output to Discord using Python logging subsystem and Discord Webhook library.

Example screenshot

Use cases

  • Easily share logs with non-technical colleagues
  • Get notified on server-side errors
  • Follow your batch job processes easily
  • Good for businesses and communities that have their messaging set up in Discord

Features

  • Minimum or no changes to a Python application needed
  • Optional color coding of messages using Discord embeds
  • Optional emoticons on messages using Unicode
  • Discord rate limiting friendly for burst of logs
  • Documentation
  • Special handling for long log messages like tracebacks to deal with Discord's 2000 character max message length

Requirements

  • Python 3.8+

Installation

With pip:

pip install python-logging-discord-handler

With Poetry:

poetry add python-logging-discord-handler

Usage

This example logs both to Discord and standard output.

First you need to

import logging

from discord_logging.handler import DiscordHandler

# See instructions below how to get a Webhook URL
webhook_url = # ...
logger = logging.getLogger()

stream_format = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
discord_format = logging.Formatter("%(message)s")

discord_handler = DiscordHandler(
    "Hello World Bot", 
    webhook_url, 
    avatar_url="https://i0.wp.com/www.theterminatorfans.com/wp-content/uploads/2012/09/the-terminator3.jpg?resize=900%2C450&ssl=1")

#discord_handler = DiscordHandler("Happy Bot", webhook_url, emojis={})
discord_handler.setFormatter(discord_format)
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(stream_format)

# Add the handlers to the Logger
logger.addHandler(discord_handler)
logger.addHandler(stream_handler)
logger.setLevel(logging.DEBUG)

logger.info("This is an info message")
logger.debug("A debug message - usually not that interesting")
logger.error("Very nasty error messgae!")

Find more examples in the examples.py source code.

How to get Discord webhook URL

  1. Go to Edit channel (gear) in Discord
  2. Choose Integrations
  3. Choose View webhooks -> New
  4. Copy URL

Webhook URL security

It is recommend that you store the webhook URL outside your source code to avoid damage in hacks or similar security incidents.

In Linux/macOS shell you can do on the command line:

export DISCORD_TEST_WEBHOOK_URL=<your webhook URL here>

For long term configuration, you can create a file storing environment variables outside your source code tree, like in your home directory. Store the export commands there.

# Text editor for a secrets.env file in your home directory on Linux
nano ~/secrets.env  

In your Linux shell session, you can then read this file and make environment variables effective using source command in your shell:

# Reads secrets.env and executes all commands there and makes them effective
# in the current shell session
source ~/secrets.env

Then you can read the environment variable in your Python code:

import os

webhook_url = os.environ["DISCORD_TEST_WEBHOOK_URL"]

Discord limitations

  • Max 2000 characters per message. See API documentation how to work around this limitation with different options. By default the bottom most lines of the log message, like a traceback, are shown.
  • Discord embeds, those that give you a logging level color bar on the left, have very hard time to deal with long lines. Embeds are disabled for long lines by default.

Log output formatting logic

The log message are converted to Discord embeds with the following logic

  • Single line log messsages are converted to embed titles
  • For multi line log messages, the first line is the embed title and the following lines are the embed description
  • Long lines or long messages cannot be convert to embeds, instead they use Discord Markdown code formattiong to preserve the readability of the output
  • A special message_break_char can be assigned to manually split long messages

Colours and emoticons

Logging messages can be decorated with colours and emoticons.

Emoji screenshot

Here are the defaults:

#: The default log level colors as hexacimal, converted int
DEFAULT_COLOURS = {
    None: 2040357,  # Unknown log level
    logging.CRITICAL: 14362664,  # Red
    logging.ERROR: 14362664,  # Red
    logging.WARNING: 16497928,  # Yellow
    logging.INFO: 2196944,  # Blue
    logging.DEBUG: 8947848,  # Gray
}


#: The default log emojis as
DEFAULT_EMOJIS = {
    None: "",  # Unknown log level
    logging.CRITICAL: "🆘",
    logging.ERROR: "❌",
    logging.WARNING: "⚠️",
    logging.INFO: "",
    logging.DEBUG: "",
}

Emoticons are disabled by default as they often make the output a bit too colourful and harder to read.

Testing and development

Manual tests

Inspect how logging output looks in Discord.

  • Checkout this Git repository
  • Set up a dummy Discord channel
  • Get its webhook URL
poetry install -E docs 
export DISCORD_TEST_WEBHOOK_URL=...
python discord_logging/examples.py

This will dump some messages to your Discord.

Automated tests

Run:

pytest

History

Originally created for Trading Strategy to follow trading bot activity.

License

MIT

Project details


Download files

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

Source Distribution

python-logging-discord-handler-0.1.2.tar.gz (9.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

File details

Details for the file python-logging-discord-handler-0.1.2.tar.gz.

File metadata

File hashes

Hashes for python-logging-discord-handler-0.1.2.tar.gz
Algorithm Hash digest
SHA256 a75ec40b76b0d101315dce00c9505e97913eb56f25d690dcb80f9d10294f7f13
MD5 1dc8c3c142391b2f945fec85e01d3972
BLAKE2b-256 a9d6ce1363f79c1762f60470d372d4b3b8cc1e7453021b7447950cddce825896

See more details on using hashes here.

File details

Details for the file python_logging_discord_handler-0.1.2-py3-none-any.whl.

File metadata

File hashes

Hashes for python_logging_discord_handler-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 e06801e7b2170a8ba7c6be89737d2624dd3d4244391a842ad8bf638c35ba2b53
MD5 0ebf129ff8413e4c96280eeb45007aac
BLAKE2b-256 85a5a7d19b6d9dc8625c77fffe7579346e9913c85f7d037bc3c47351aeb206b3

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page