[Feature][Logging]#25
Merged
shamikkarkhanis merged 5 commits intomainfrom Jan 13, 2026
Merged
Conversation
Contributor
Reviewer's GuideRefactors the logging system to use a colored stdout-based root logger, introduces a reusable logger accessor, and adds structured logging and error handling to the sync and ping cogs while simplifying cog construction and Discord client startup logging behavior. Sequence diagram for /ping command handling with loggingsequenceDiagram
actor User
participant DiscordGateway
participant BotInstance
participant PingCog as Ping
participant LoggingModule
participant RootLogger
participant StdoutHandler
participant ColoredFormatter
User->>DiscordGateway: /ping command
DiscordGateway->>BotInstance: InteractionCreate(ping)
BotInstance->>PingCog: ping(interaction)
activate PingCog
PingCog->>PingCog: calculate_latency()
PingCog->>LoggingModule: get_logger(__name__)
LoggingModule-->>PingCog: logging_Logger
PingCog->>RootLogger: info("/ping invoked user: ...")
RootLogger->>StdoutHandler: emit(LogRecord)
StdoutHandler->>ColoredFormatter: format(LogRecord)
ColoredFormatter-->>StdoutHandler: formatted_colored_string
StdoutHandler-->>RootLogger: write_to_stdout()
PingCog->>BotInstance: interaction.response.send_message(embed)
BotInstance->>DiscordGateway: SendMessage(Ping embed)
DiscordGateway-->>User: Show ping latency
deactivate PingCog
Note over PingCog,RootLogger: On exception
User-->>DiscordGateway: /ping command
DiscordGateway-->>BotInstance: InteractionCreate(ping)
BotInstance-->>PingCog: ping(interaction)
activate PingCog
PingCog->>RootLogger: exception("/ping attempted user")
RootLogger->>StdoutHandler: emit(LogRecord)
StdoutHandler->>ColoredFormatter: format(LogRecord)
ColoredFormatter-->>StdoutHandler: formatted_colored_string
StdoutHandler-->>RootLogger: write_to_stdout()
PingCog-->>BotInstance: interaction.response.send_message(generic_error)
BotInstance-->>DiscordGateway: SendMessage(Generic error)
DiscordGateway-->>User: Show generic failure message
deactivate PingCog
Class diagram for updated logging and Discord cogsclassDiagram
direction LR
class logging_Formatter {
}
class ColoredFormatter {
+level_colors dict
+name_color str
+reset str
+__init__(fmt: str, datefmt: str)
+format(record: logging_LogRecord) str
}
class Sync {
-logger logging_Logger
+__init__() None
+_sync_commands() list
+sync(ctx: commands_Context) None
+sync_slash(interaction: discord_Interaction) None
}
class Ping {
-logger logging_Logger
+__init__() None
+ping(interaction: discord_Interaction) None
}
class LoggingModule {
+LOG_FORMAT str
+DATE_FORMAT str
+get_logger(name: str) logging_Logger
+setup_logging(level: int) None
}
ColoredFormatter --|> logging_Formatter
Sync ..> LoggingModule : uses_get_logger
Ping ..> LoggingModule : uses_get_logger
LoggingModule ..> ColoredFormatter : uses_in_setup_logging
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Contributor
There was a problem hiding this comment.
Hey - I've found 3 issues, and left some high level feedback:
- In
setup_logging, thelogsdirectory is still created but no file handler writes to it anymore, so either reintroduce a file/rotating handler or remove the directory creation to avoid dead code. - For the new logging calls, prefer logger argument interpolation (e.g.
self.logger.info("/ping invoked user: %s guild: %s", interaction.user.id, interaction.guild_id)) instead of f-strings so that formatting cost is only incurred when the message is actually emitted.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- In `setup_logging`, the `logs` directory is still created but no file handler writes to it anymore, so either reintroduce a file/rotating handler or remove the directory creation to avoid dead code.
- For the new logging calls, prefer logger argument interpolation (e.g. `self.logger.info("/ping invoked user: %s guild: %s", interaction.user.id, interaction.guild_id)`) instead of f-strings so that formatting cost is only incurred when the message is actually emitted.
## Individual Comments
### Comment 1
<location> `capy_discord/logging.py:64-66` </location>
<code_context>
+ formatter = ColoredFormatter(LOG_FORMAT, datefmt=DATE_FORMAT)
+ handler.setFormatter(formatter)
+
+ # Create a log directory if it doesn't exist
log_dir = Path("logs")
log_dir.mkdir(exist_ok=True)
- # Root logger
</code_context>
<issue_to_address>
**suggestion:** The `logs` directory is created but never used now that file logging has been removed.
Consider either removing this block or adding a file handler that writes to `log_dir` so the directory creation isn’t dead code and doesn’t confuse future readers.
</issue_to_address>
### Comment 2
<location> `capy_discord/logging.py:68` </location>
<code_context>
- )
- file_handler.setFormatter(logging.Formatter(log_format))
- logger.addHandler(file_handler)
+ # Removing previous handlers to avoid duplicate logs from discord after setup_logging invokation
+ if root_logger.hasHandlers():
+ root_logger.handlers.clear()
</code_context>
<issue_to_address>
**nitpick (typo):** Fix minor typo in the comment describing handler removal.
Please change "invokation" to "invocation" to keep the comment professional and clear.
```suggestion
# Removing previous handlers to avoid duplicate logs from discord after setup_logging invocation
```
</issue_to_address>
### Comment 3
<location> `capy_discord/exts/tools/ping.py:27-29` </location>
<code_context>
+
+ await interaction.response.send_message(embed=embed)
+
+ except Exception:
+ self.logger.exception("/ping attempted user")
+ await interaction.response.send_message("We're sorry, this interaction failed. Please contact an admin.")
</code_context>
<issue_to_address>
**suggestion:** Align the error log message with the successful path by adding more context.
Right now the success path for `/ping` logs the invoking user and guild, but the exception path logs only a static string. Please include `interaction.user.id` and `interaction.guild_id` in the exception message (while still using `logger.exception` for the traceback) so failures can be tied to specific servers and users.
```suggestion
except Exception:
self.logger.exception(
f"/ping failed user: {interaction.user.id} guild: {interaction.guild_id}"
)
await interaction.response.send_message(
"We're sorry, this interaction failed. Please contact an admin."
)
```
</issue_to_address>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary by Sourcery
Introduce a colorized stdout-based logging configuration and integrate structured logging into core Discord command cogs.
New Features:
Enhancements: