diff options
| author | 2020-02-21 11:14:03 +0000 | |
|---|---|---|
| committer | 2020-02-21 11:14:03 +0000 | |
| commit | 215483e390b7f5636cf1d46c96c216ef0d05cb03 (patch) | |
| tree | 8b731e532a7577a8ffa0923ff5ce8c9247c0d98e | |
| parent | Attach extra information on a command error (diff) | |
Add basic sentry usage for command errors giving user information and command context.
| -rw-r--r-- | bot/__main__.py | 6 | ||||
| -rw-r--r-- | bot/api.py | 74 | ||||
| -rw-r--r-- | bot/bot.py | 2 | ||||
| -rw-r--r-- | bot/cogs/error_handler.py | 13 |
4 files changed, 10 insertions, 85 deletions
diff --git a/bot/__main__.py b/bot/__main__.py index 4f51a08cc..51bba6191 100644 --- a/bot/__main__.py +++ b/bot/__main__.py @@ -1,12 +1,16 @@ import discord import sentry_sdk from discord.ext.commands import when_mentioned_or +from sentry_sdk.integrations.aiohttp import AioHttpIntegration from bot import patches from bot.bot import Bot from bot.constants import Bot as BotConfig, DEBUG_MODE -sentry_sdk.init(BotConfig.sentry_dsn) +sentry_sdk.init( + dsn=BotConfig.sentry_dsn, + integrations=[AioHttpIntegration()] +) bot = Bot( command_prefix=when_mentioned_or(BotConfig.prefix), diff --git a/bot/api.py b/bot/api.py index 56db99828..fb126b384 100644 --- a/bot/api.py +++ b/bot/api.py @@ -141,77 +141,3 @@ def loop_is_running() -> bool: except RuntimeError: return False return True - - -class APILoggingHandler(logging.StreamHandler): - """Site API logging handler.""" - - def __init__(self, client: APIClient): - logging.StreamHandler.__init__(self) - self.client = client - - # internal batch of shipoff tasks that must not be scheduled - # on the event loop yet - scheduled when the event loop is ready. - self.queue = [] - - async def ship_off(self, payload: dict) -> None: - """Ship log payload to the logging API.""" - try: - await self.client.post('logs', json=payload) - except ResponseCodeError as err: - log.warning( - "Cannot send logging record to the site, got code %d.", - err.response.status, - extra={'via_handler': True} - ) - except Exception as err: - log.warning( - "Cannot send logging record to the site: %r", - err, - extra={'via_handler': True} - ) - - def emit(self, record: logging.LogRecord) -> None: - """ - Determine if a log record should be shipped to the logging API. - - If the asyncio event loop is not yet running, log records will instead be put in a queue - which will be consumed once the event loop is running. - - The following two conditions are set: - 1. Do not log anything below DEBUG (only applies to the monkeypatched `TRACE` level) - 2. Ignore log records originating from this logging handler itself to prevent infinite recursion - """ - if ( - record.levelno >= logging.DEBUG - and not record.__dict__.get('via_handler') - ): - payload = { - 'application': 'bot', - 'logger_name': record.name, - 'level': record.levelname.lower(), - 'module': record.module, - 'line': record.lineno, - 'message': self.format(record) - } - - task = self.ship_off(payload) - if not loop_is_running(): - self.queue.append(task) - else: - asyncio.create_task(task) - self.schedule_queued_tasks() - - def schedule_queued_tasks(self) -> None: - """Consume the queue and schedule the logging of each queued record.""" - for task in self.queue: - asyncio.create_task(task) - - if self.queue: - log.debug( - "Scheduled %d pending logging tasks.", - len(self.queue), - extra={'via_handler': True} - ) - - self.queue.clear() diff --git a/bot/bot.py b/bot/bot.py index 8f808272f..cecee7b68 100644 --- a/bot/bot.py +++ b/bot/bot.py @@ -27,8 +27,6 @@ class Bot(commands.Bot): self.http_session: Optional[aiohttp.ClientSession] = None self.api_client = api.APIClient(loop=self.loop, connector=self.connector) - log.addHandler(api.APILoggingHandler(self.api_client)) - def add_cog(self, cog: commands.Cog) -> None: """Adds a "cog" to the bot and logs the operation.""" super().add_cog(cog) diff --git a/bot/cogs/error_handler.py b/bot/cogs/error_handler.py index 021753081..e76f1a086 100644 --- a/bot/cogs/error_handler.py +++ b/bot/cogs/error_handler.py @@ -15,7 +15,7 @@ from discord.ext.commands import ( UserInputError, ) from discord.ext.commands import Cog, Context -from sentry_sdk import configure_scope +from sentry_sdk import capture_exception, configure_scope from bot.api import ResponseCodeError from bot.bot import Bot @@ -148,21 +148,18 @@ class ErrorHandler(Cog): f"Sorry, an unexpected error occurred. Please let us know!\n\n" f"```{e.__class__.__name__}: {e}```" ) - log.error( - f"Error executing command invoked by {ctx.message.author}: {ctx.message.content}" - ) with configure_scope() as scope: scope.user = { - "username": ctx.author.username, - "id": ctx.author.id + "id": ctx.author.id, + "username": str(ctx.author) } scope.set_tag("command", ctx.command.qualified_name) scope.set_tag("message_id", ctx.message.id) scope.set_extra("full_message", ctx.message.content) - - raise e + + capture_exception(e) def setup(bot: Bot) -> None: |