Created
August 13, 2020 15:53
-
-
Save MicaelJarniac/36971acc790e4fedc90dda9c6697d0b9 to your computer and use it in GitHub Desktop.
Discord Logging Handler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
from discord_webhook import DiscordWebhook, DiscordEmbed | |
import config | |
class DiscordHandler(logging.Handler): | |
""" | |
Custom handler to send logs to Discord | |
""" | |
colors = { | |
"DEBUG": 65280, | |
"INFO": 65535, | |
"WARNING": 16776960, | |
"ERROR": 16750848, | |
"CRITICAL": 16711680, | |
"default": 0, | |
} | |
def __init__(self): | |
# TODO Maybe super()? | |
logging.Handler.__init__(self) | |
url = config.DISCORD_WEBHOOK_URL | |
self.discordWebhook = DiscordWebhook(url=url, username=config.DISCORD_WEBHOOK_USERNAME, avatar_url=config.DISCORD_WEBHOOK_AVATAR) | |
def emit(self, record): | |
desc = [ | |
record.message, | |
record.exc_info, | |
"`" + str(record.funcName) + "` : `" + str(record.lineno) + "`", | |
record.stack_info | |
] | |
filteredDesc = [record for record in desc if record is not None] | |
try: | |
color = self.colors[record.levelname] | |
except KeyError: | |
color = self.colors["default"] | |
embed = DiscordEmbed( | |
title=record.name, | |
description="\n".join(filteredDesc), | |
color=color) | |
embed.set_footer(text=record.levelname) | |
embed.set_timestamp(record.created) | |
self.discordWebhook.add_embed(embed) | |
self.discordWebhook.execute() |
Upon further testing, it seems to me that instantiating DiscordWebhook inside DiscordHandler's init can end up generating many duplicate webhooks depending on logging speed, and I believe that's because each new log sent to the handler adds itself to the already existing DiscordWebhook instance, and when in rapid succession, that instance might end up being shared by multiple log messages, thus generating duplicate webhooks.
I've moved the instantiation of it to inside emit, and that seems to have sorted this issue, although I'm not sure if it's the best way around it.
The rate limiting seems to still he happening, however, as some log messages are still not going through.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I believe there might be some rate limiting into play somewhere. When I have the Discord logging level set too low, there are way too many webhooks being sent, and it seems quite a few don't make it through. I only started receiving webhooks for ERROR when I set the level up to WARNING, otherwise there'd be too many DEBUG and INFO that many didn't make it through.