Skip to content

Commit

Permalink
Exclude internetarchive's internal logging from Discord
Browse files Browse the repository at this point in the history
  • Loading branch information
HebaruSan committed Oct 19, 2024
1 parent 9831903 commit a5233c7
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions netkan/netkan/notifications.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import os
import sys
import re
import logging
from typing import Iterable, Type, Optional
from types import TracebackType
import discord

# A regex to prevent internetarchive's errors from going to Discord
NOT_IA_PATTERN = re.compile('^(?!.*internetarchive)')


def catch_all(type_: Type[BaseException], value: BaseException, traceback: Optional[TracebackType]) -> None:
# Log an error for Discord
Expand All @@ -16,16 +20,19 @@ def catch_all(type_: Type[BaseException], value: BaseException, traceback: Optio

class DiscordLogHandler(logging.Handler):

def __init__(self, webhook_id: str, webhook_token: str) -> None:
def __init__(self, webhook_id: str, webhook_token: str,
logger_filter: re.Pattern[str]) -> None:
super().__init__()
self.webhook = discord.Webhook.partial(webhook_id, webhook_token,
adapter=discord.RequestsWebhookAdapter())
self.logger_filter = logger_filter

def emit(self, record: logging.LogRecord) -> None:
fmt = self.format(record)
as_code = "\n" in fmt
for part in self._message_parts(fmt, as_code):
self.webhook.send(part)
if self.logger_filter.match(record.name):
fmt = self.format(record)
as_code = "\n" in fmt
for part in self._message_parts(fmt, as_code):
self.webhook.send(part)

@staticmethod
def _message_parts(msg: str, as_code: bool, max_len: int = 2000) -> Iterable[str]:
Expand All @@ -47,7 +54,7 @@ def setup_log_handler(debug: bool = False) -> bool:
discord_webhook_id = os.environ.get('DISCORD_WEBHOOK_ID')
discord_webhook_token = os.environ.get('DISCORD_WEBHOOK_TOKEN')
if discord_webhook_id and discord_webhook_token:
handler = DiscordLogHandler(discord_webhook_id, discord_webhook_token)
handler = DiscordLogHandler(discord_webhook_id, discord_webhook_token, NOT_IA_PATTERN)
handler.setLevel(logging.ERROR)
logging.getLogger('').addHandler(handler)
return True
Expand Down

0 comments on commit a5233c7

Please sign in to comment.