Skip to content

Commit

Permalink
Use new logging util from bot-core
Browse files Browse the repository at this point in the history
  • Loading branch information
ChrisLovering committed Nov 25, 2023
1 parent 0171617 commit 27a12e1
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 50 deletions.
18 changes: 0 additions & 18 deletions bot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
7 changes: 4 additions & 3 deletions bot/__main__.py
Original file line number Diff line number Diff line change
@@ -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."""
Expand Down
61 changes: 32 additions & 29 deletions bot/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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:
Expand All @@ -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)

0 comments on commit 27a12e1

Please sign in to comment.