From 27a12e1994e80502a2608f35431d2a9df82a8b5a Mon Sep 17 00:00:00 2001 From: Chris Lovering Date: Sat, 25 Nov 2023 22:01:47 +0000 Subject: [PATCH] Use new logging util from bot-core --- bot/__init__.py | 18 --------------- bot/__main__.py | 7 +++--- bot/log.py | 61 ++++++++++++++++++++++++++----------------------- 3 files changed, 36 insertions(+), 50 deletions(-) diff --git a/bot/__init__.py b/bot/__init__.py index 9ae64c2ea6..67165073e1 100644 --- a/bot/__init__.py +++ b/bot/__init__.py @@ -6,35 +6,17 @@ pass import asyncio -import logging import os from typing import TYPE_CHECKING import arrow -import sentry_sdk from pydis_core.utils import apply_monkey_patches -from sentry_sdk.integrations.logging import LoggingIntegration -from sentry_sdk.integrations.redis import RedisIntegration from bot import log if TYPE_CHECKING: from bot.bot import Bot -sentry_logging = LoggingIntegration( - level=logging.DEBUG, - event_level=logging.WARNING -) - -sentry_sdk.init( - dsn=os.environ.get("BOT_SENTRY_DSN"), - integrations=[ - sentry_logging, - RedisIntegration() - ], - release=f"sir-lancebot@{os.environ.get('GIT_SHA', 'foobar')}" -) - log.setup() # Set timestamp of when execution started (approximately) diff --git a/bot/__main__.py b/bot/__main__.py index 1b6b9f1e21..bacb2fdd69 100644 --- a/bot/__main__.py +++ b/bot/__main__.py @@ -1,20 +1,21 @@ import asyncio -import logging import aiohttp import discord from async_rediscache import RedisSession from discord.ext import commands from pydis_core import StartupError +from pydis_core.utils.logging import get_logger from redis import RedisError import bot from bot import constants from bot.bot import Bot +from bot.log import setup_sentry from bot.utils.decorators import whitelist_check -log = logging.getLogger(__name__) - +log = get_logger(__name__) +setup_sentry() async def _create_redis_session() -> RedisSession: """Create and connect to a redis session.""" diff --git a/bot/log.py b/bot/log.py index a87a836ad8..b4431bc3df 100644 --- a/bot/log.py +++ b/bot/log.py @@ -5,31 +5,28 @@ from pathlib import Path import coloredlogs +import sentry_sdk +from pydis_core.utils import logging as core_logging +from sentry_sdk.integrations.logging import LoggingIntegration +from sentry_sdk.integrations.redis import RedisIntegration from bot.constants import Logging def setup() -> None: """Set up loggers.""" - # Configure the "TRACE" logging level (e.g. "log.trace(message)") - logging.TRACE = 5 - logging.addLevelName(logging.TRACE, "TRACE") - logging.Logger.trace = _monkeypatch_trace - - format_string = "%(asctime)s | %(name)s | %(levelname)s | %(message)s" - log_format = logging.Formatter(format_string) - root_logger = logging.getLogger() + root_logger = core_logging.get_logger() if Logging.file_logs: # Set up file logging - log_file = Path("logs/sir-lancebot.log") + log_file = Path("logs", "sir-lancebot.log") log_file.parent.mkdir(exist_ok=True) # File handler rotates logs every 5 MB file_handler = logging.handlers.RotatingFileHandler( log_file, maxBytes=5 * (2 ** 20), backupCount=10, encoding="utf-8", ) - file_handler.setFormatter(log_format) + file_handler.setFormatter(core_logging.log_format) root_logger.addHandler(file_handler) if "COLOREDLOGS_LEVEL_STYLES" not in os.environ: @@ -41,32 +38,38 @@ def setup() -> None: } if "COLOREDLOGS_LOG_FORMAT" not in os.environ: - coloredlogs.DEFAULT_LOG_FORMAT = format_string + coloredlogs.DEFAULT_LOG_FORMAT = core_logging.log_format._fmt - coloredlogs.install(level=logging.TRACE, stream=sys.stdout) + coloredlogs.install(level=core_logging.TRACE_LEVEL, stream=sys.stdout) root_logger.setLevel(logging.DEBUG if Logging.debug else logging.INFO) - # Silence irrelevant loggers - logging.getLogger("discord").setLevel(logging.ERROR) - logging.getLogger("websockets").setLevel(logging.ERROR) + logging.getLogger("PIL").setLevel(logging.ERROR) logging.getLogger("matplotlib").setLevel(logging.ERROR) - logging.getLogger("async_rediscache").setLevel(logging.WARNING) _set_trace_loggers() - root_logger.info("Logging initialization complete") -def _monkeypatch_trace(self: logging.Logger, msg: str, *args, **kwargs) -> None: - """ - Log 'msg % args' with severity 'TRACE'. +def setup_sentry() -> None: + """Set up the Sentry logging integrations.""" + sentry_logging = LoggingIntegration( + level=logging.DEBUG, + event_level=logging.WARNING + ) - To pass exception information, use the keyword argument exc_info with a true value, e.g. - logger.trace("Houston, we have an %s", "interesting problem", exc_info=1) - """ - if self.isEnabledFor(logging.TRACE): - self._log(logging.TRACE, msg, args, **kwargs) + sentry_sdk.init( + dsn=os.environ.get("BOT_SENTRY_DSN"), + integrations=[ + sentry_logging, + RedisIntegration(), + ], + release=f"bot@{os.environ.get('GIT_SHA')}", + traces_sample_rate=0.5, + _experiments={ + "profiles_sample_rate": 0.5, + }, + ) def _set_trace_loggers() -> None: @@ -84,13 +87,13 @@ def _set_trace_loggers() -> None: level_filter = Logging.trace_loggers if level_filter: if level_filter.startswith("*"): - logging.getLogger().setLevel(logging.TRACE) + core_logging.get_logger().setLevel(core_logging.TRACE_LEVEL) elif level_filter.startswith("!"): - logging.getLogger().setLevel(logging.TRACE) + core_logging.get_logger().setLevel(core_logging.TRACE_LEVEL) for logger_name in level_filter.strip("!,").split(","): - logging.getLogger(logger_name).setLevel(logging.DEBUG) + core_logging.get_logger(logger_name).setLevel(logging.DEBUG) else: for logger_name in level_filter.strip(",").split(","): - logging.getLogger(logger_name).setLevel(logging.TRACE) + core_logging.get_logger(logger_name).setLevel(core_logging.TRACE_LEVEL)