Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Exclude internetarchive's internal logging from Discord #346

Merged
merged 1 commit into from
Oct 19, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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