Skip to content

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

  1. Command execution begins
  2. Command context captures received_at timestamp
  3. Command executes
  4. On completion (success or failure):
  5. Calculate processing time
  6. Create log entry with all context data
  7. Insert into database

Command Logging Integration Points

Command logging is integrated at two key points in the command execution pipeline:

  1. Success Logging
  2. Location: Stingbatbot.Consumer.try_execute_command/3
  3. Added after successful command execution
  4. Captures successful command execution with "success" status

  5. Failure Logging

  6. Location: Stingbatbot.Consumer.log_and_send_error/4
  7. Added to capture failed command execution
  8. 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 to nil for DM commands
  • Statistics can be filtered to show only DM commands by passing nil as the guild_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

  1. Querying and Analysis
  2. Add functions to query logs by various criteria
  3. Implement command performance analysis
  4. Add aggregation functions for statistics

  5. Performance Optimization

  6. Consider batch inserts if volume becomes high
  7. Add indexes for common query patterns
  8. Implement log rotation/archival if needed

  9. Monitoring

  10. Add alerts for command failures
  11. Track command usage patterns
  12. 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

  1. ✅ Create migration for command_logs table
  2. ✅ Create CommandLog schema module
  3. ✅ Create CommandLog.Context module
  4. ✅ Implement logging functionality
  5. ✅ Add command logging to execution pipeline
  6. ✅ Add schema tests
  7. ✅ Add context tests
  8. ✅ Add integration tests
  9. ✅ Add performance indexes
  10. ✅ Update documentation

Lessons Learned

  1. Context Structure
  2. Command context should include command_name for proper logging
  3. Author information should be accessed via context.author.id
  4. DM support requires proper handling of nil guild_id

  5. Schema Design

  6. Use timestamps() macro for automatic timestamp handling
  7. Keep schema focused on essential fields
  8. Make guild_id optional to support DMs

  9. Testing

  10. Use test helpers for realistic data
  11. Prefer dependency injection over mocking
  12. Keep test files clean and focused
  13. Test both guild and DM scenarios

  14. Error Handling

  15. Format error messages consistently
  16. Use clear status values ("success" or "error")

  17. Performance

  18. Calculate processing time in milliseconds
  19. Add appropriate indexes for common queries