Command Logging System¶
Overview¶
The Command Logging System provides a way to track and analyze command usage in Stingbatbot. It records essential information about each command execution, including timing, success/failure status, and contextual data. The system handles both guild commands and direct messages (DMs).
Module Locations¶
- Schema:
lib/stingbatbot/schemas/command_log.ex
- Context:
lib/stingbatbot/contexts/command_log.ex
- Migration:
priv/repo/migrations/20250404144205_create_command_logs.exs
Schema¶
CommandLog¶
The Stingbatbot.CommandLog
schema defines the structure for command log entries with the following fields:
user_id
: Discord user ID who executed the command (required, non-empty string)guild_id
: Discord guild ID where the command was executed (optional, nil for DMs)channel_id
: Discord channel ID where the command was executed (required, non-empty string)command_name
: Name of the command (e.g., "attack", "check") (required, non-empty string)command_args
: Arguments passed to the command (optional)status
: Success/failure status (required, must be either "success" or "error")error_message
: Exception/error message if the command failed (optional)processing_time_ms
: Time taken to process the command in milliseconds (required, non-negative integer)inserted_at
: Timestamp when the log entry was created (automatically handled by timestamps())
Context Module¶
The Stingbatbot.CommandLog.Context
module provides the business logic for command logging. It handles:
- Creating new command log entries for both guild commands and DMs
- Calculating processing time
- Managing success/failure status
- Storing error messages when applicable
- Providing statistics for both guild commands and DMs
Implementation Details¶
Processing Time Calculation¶
The system calculates processing time by comparing the command's start time (received_at
) with the current time when logging occurs. This provides accurate timing information for performance analysis.
Logging Flow¶
- Command execution begins
- Command context captures
received_at
timestamp - Command executes
- On completion (success or failure):
- Calculate processing time
- Create log entry with all context data
- Insert into database
Command Logging Integration Points¶
Command logging is integrated at two key points in the command execution pipeline:
- Success Logging
- Location:
Stingbatbot.Consumer.try_execute_command/3
- Added after successful command execution
-
Captures successful command execution with "success" status
-
Failure Logging
- Location:
Stingbatbot.Consumer.log_and_send_error/4
- Added to capture failed command execution
- Includes error message in the log entry with "error" status
Command Arguments¶
Command arguments are stored as-is from the command context, without additional parsing or processing.
DM Support¶
The command logging system fully supports direct messages (DMs) with the following considerations:
guild_id
is set tonil
for DM commands- Statistics can be filtered to show only DM commands by passing
nil
as theguild_id
parameter - All other fields (user_id, channel_id, etc.) are populated as normal
- Processing time and error handling work the same way for DMs and guild commands
Future Considerations¶
- Querying and Analysis
- Add functions to query logs by various criteria
- Implement command performance analysis
-
Add aggregation functions for statistics
-
Performance Optimization
- Consider batch inserts if volume becomes high
- Add indexes for common query patterns
-
Implement log rotation/archival if needed
-
Monitoring
- Add alerts for command failures
- Track command usage patterns
- Monitor processing time trends
Testing Plan¶
Schema Tests¶
- Validate required fields
- Ensure proper status values
- Verify timestamp handling
- Test field constraints
- Verify DM support with nil guild_id
Context Tests¶
- Verify successful command logging for both guild commands and DMs
- Test error case handling
- Validate processing time calculation
- Ensure proper error message storage
- Verify statistics functions for both guild commands and DMs
Implementation Checklist¶
- ✅ Create migration for command_logs table
- ✅ Create CommandLog schema module
- ✅ Create CommandLog.Context module
- ✅ Implement logging functionality
- ✅ Add command logging to execution pipeline
- ✅ Add schema tests
- ✅ Add context tests
- ✅ Add integration tests
- ✅ Add performance indexes
- ✅ Update documentation
Lessons Learned¶
- Context Structure
- Command context should include
command_name
for proper logging - Author information should be accessed via
context.author.id
-
DM support requires proper handling of nil guild_id
-
Schema Design
- Use
timestamps()
macro for automatic timestamp handling - Keep schema focused on essential fields
-
Make guild_id optional to support DMs
-
Testing
- Use test helpers for realistic data
- Prefer dependency injection over mocking
- Keep test files clean and focused
-
Test both guild and DM scenarios
-
Error Handling
- Format error messages consistently
-
Use clear status values ("success" or "error")
-
Performance
- Calculate processing time in milliseconds
- Add appropriate indexes for common queries