Skip to content

Commit

Permalink
Merge pull request #346 from HebaruSan/fix/ia-logging
Browse files Browse the repository at this point in the history
Exclude internetarchive's internal logging from Discord
  • Loading branch information
HebaruSan authored Oct 19, 2024
2 parents 9831903 + a5233c7 commit 6b9e530
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 6b9e530

Please sign in to comment.