AI-powered log analysis for Ruby applications
DebugAI is a command-line tool that analyzes your Ruby/Rails application logs and provides intelligent error diagnosis using AI. Instead of manually sifting through logs, let AI help you understand errors, find root causes, and get actionable solutions.
- 🔍 Smart log parsing - Automatically extracts errors from Rails logs
- 🤖 AI-powered analysis - Get intelligent diagnostics and solutions in Spanish or English
- 📊 Rich context extraction - Captures request info, backtraces, and environment details
- 🔧 Advanced code analysis - Analyzes source code files from stacktraces for deeper insights
- 📝 Log context integration - Includes log context around errors for better understanding
- 🇪🇸 Multilingual support - Get responses in Spanish (default) or English
- 🕐 Time-based filtering - Analyze errors in specific time ranges
- 🎯 Error type filtering - Focus on specific error classes
- 🔴 Live analysis - Real-time error analysis from log streams
- 🌐 Multiple AI providers - OpenAI, Anthropic, local models (Ollama, LM Studio)
- 💎 Ruby-focused - Understands Rails log formats and Ruby stack traces
- 📱 Simple CLI - Easy to integrate into your debugging workflow
gem install debug_aiCreate a .env file in your project root or set environment variables:
# AI Provider Configuration
DEBUG_AI_API_URL=http://localhost:11434/v1/chat/completions # Ollama
DEBUG_AI_MODEL=codellama:7b-instruct
DEBUG_AI_API_KEY=your_api_key_here # Only needed for remote APIs
DEBUG_AI_TIMEOUT=60
DEBUG_AI_MAX_RETRIES=3
DEBUG_AI_VERBOSE=true# Ollama
DEBUG_AI_API_URL=http://localhost:11434/v1/chat/completions
DEBUG_AI_MODEL=codellama:7b-instruct
# LM Studio
DEBUG_AI_API_URL=http://localhost:1234/v1/chat/completions
DEBUG_AI_MODEL=local-model# OpenAI
DEBUG_AI_API_URL=https://api.openai.com/v1/chat/completions
DEBUG_AI_MODEL=gpt-4
DEBUG_AI_API_KEY=sk-...
# Anthropic Claude
DEBUG_AI_API_URL=https://api.anthropic.com/v1/messages
DEBUG_AI_MODEL=claude-3-sonnet-20240229
DEBUG_AI_API_KEY=sk-ant-...# Code analysis settings
DEBUG_AI_PROJECT_ROOT=/path/to/your/project # Auto-detected if not set
DEBUG_AI_MAX_FILES_CONTEXT=10 # Max files to analyze
DEBUG_AI_CODE_CONTEXT_LINES=5 # Lines around error location
# Log context settings
DEBUG_AI_LOG_CONTEXT_WINDOW=10 # Minutes around error
DEBUG_AI_MAX_LOG_LINES=100 # Max log lines to include
# Language and response settings
DEBUG_AI_RESPONSE_LANGUAGE=es # Default response language (es/en)
DEBUG_AI_INCLUDE_CODE_CONTEXT=false # Enable by default
DEBUG_AI_INCLUDE_LOG_CONTEXT=false # Enable by defaultWhen enabled, DebugAI analyzes the actual source code files mentioned in stack traces:
- Code extraction: Gets the exact lines causing the error
- Method context: Shows the complete method where the error occurs
- Related files: Finds and analyzes related models, controllers, and views
- Dependency analysis: Shows requires, includes, and imports
# Enable code analysis
debug_ai analyze log/production.log --with-codeProvides comprehensive log context around errors:
- Temporal context: Shows log entries before and after the error
- Related requests: Finds other requests in the same time window
- Performance metrics: Extracts timing and status information
- Request correlation: Links errors to their originating requests
# Enable log context
debug_ai analyze log/production.log --with-logsGet AI responses in your preferred language:
- Spanish (default):
--language es- Detailed analysis in Spanish - English:
--language en- Analysis in English
# Spanish analysis (default)
debug_ai analyze log/production.log --language es
# English analysis
debug_ai analyze log/production.log --language enFor the most comprehensive analysis, combine all features:
# Complete analysis: code + logs + Spanish
debug_ai analyze log/production.log --with-code --with-logs --language es
# Focus on specific errors with full context
debug_ai analyze log/production.log --error NoMethodError --with-code --with-logs# Simple analysis
debug_ai analyze log/production.log
# Advanced analysis (recommended)
debug_ai analyze log/production.log --with-code --with-logs --language es
# Analyze only the last 5 errors with code context
debug_ai analyze log/production.log --count 5 --with-code# Filter by error type with code analysis
debug_ai analyze log/production.log --error NoMethodError --with-code
# Analyze errors in a time range with log context
debug_ai analyze log/production.log --since "2023-10-04 14:00" --until "2023-10-04 15:00" --with-logs
# Verbose output with full context
debug_ai analyze log/production.log --verbose --with-code --with-logs# Real-time analysis with full context
tail -f log/production.log | debug_ai analyze --live --with-logs --language es
# Monitor development logs with code analysis
tail -f log/development.log | debug_ai analyze --live --with-code --verbose🔍 Analyzing log file: log/production.log
🤖 Using AI model: codellama:7b-instruct
📝 Language: Español
🔧 Advanced features: Code(true) Logs(true)
============================================================
📊 Found 3 error(s) to analyze:
1. NoMethodError: undefined method `charge' for nil:NilClass
⏰ 2023-10-04 14:31:15
🌐 POST /users/456/payments
🎯 PaymentsController#create
🤖 Análisis de IA:
----------------------------------------
🔍 **ANÁLISIS DEL PROBLEMA:**
- El método `charge` se está llamando en un objeto nil
- El procesador de pagos no se inicializó correctamente
- Error ocurrido en app/models/payment.rb línea 25
🎯 **LOCALIZACIÓN EXACTA:**
- Archivo: app/models/payment.rb:25
- Método: process_payment
- Variable problemática: payment_processor (es nil)
📄 **CÓDIGO EN app/models/payment.rb:**
📋 Contexto:
23: def process_payment
24: payment_processor = find_processor
➤ 25: payment_processor.charge(amount)
26: end
🔍 Variables en línea: payment_processor, amount
🔗 Llamadas a métodos: charge
📝 **CONTEXTO DE LOGS:**
🕐 14:31:15.245 - ERROR: undefined method `charge' for nil:NilClass
🕐 14:31:15.237 - INFO: Parameters: {"user_id"=>"456", "amount"=>"100.00"}
🕐 14:31:15.236 - INFO: Processing by PaymentsController#create
💡 **SOLUCIÓN PRÁCTICA:**
```ruby
def process_payment
payment_processor = find_processor
if payment_processor.nil?
raise PaymentProcessorError, "No payment processor available"
end
payment_processor.charge(amount)
end
🛡️ PREVENCIÓN:
- Validar que payment_processor no sea nil antes de usarlo
- Implementar fallback para procesadores de pago
- Añadir logs para debugging de inicialización
============================================================
## 🔧 CLI Commands
### `analyze` - Analyze log files for errors
```bash
debug_ai analyze [file] [options]
Options:
-f, --file FILE Log file to analyze
-l, --live Read from stdin (for piping)
-c, --count N Number of recent errors to analyze (default: 10)
-s, --since TIME Analyze errors since timestamp (YYYY-MM-DD HH:MM)
-u, --until TIME Analyze errors until timestamp (YYYY-MM-DD HH:MM)
-e, --error CLASS Filter by error class (e.g., NoMethodError)
--with-code Include source code analysis from stacktraces
--with-logs Include log context around errors
--language LANG Response language: es (español) or en (english)
-v, --verbose Verbose output
For the most comprehensive analysis, use the advanced options:
# Complete analysis with code and log context in Spanish
debug_ai analyze log/production.log --with-code --with-logs --language es
# Focus on specific error types with code analysis
debug_ai analyze log/production.log --error NoMethodError --with-code
# Live monitoring with full context
tail -f log/production.log | debug_ai analyze --live --with-logs --language esdebug_ai search --pattern "NoMethodError" --file log/production.logdebug_ai configdebug_ai versionDebugAI currently supports Rails log format. The parser recognizes:
- Error entries: Lines containing Ruby exceptions
- Request context: HTTP method, path, controller, action
- Stack traces: Ruby backtraces with file locations
- Timing information: Request duration and timestamps
- Parameters: Request parameters (sensitive data filtered)
I, [2023-10-04T14:30:00.123456 #12345] INFO -- : Started GET "/users/123" for 127.0.0.1
I, [2023-10-04T14:30:00.125456 #12345] INFO -- : Processing by UsersController#show as HTML
E, [2023-10-04T14:30:00.130456 #12345] ERROR -- : ActiveRecord::RecordNotFound: Couldn't find User with 'id'=123
app/controllers/users_controller.rb:15:in `show'
app/controllers/application_controller.rb:10:in `rescue_action'
I, [2023-10-04T14:30:00.135456 #12345] INFO -- : Completed 404 Not Found in 10ms
DebugAI provides specialized analysis for common Ruby/Rails errors:
- NoMethodError - Undefined method calls
- NameError - Undefined constants or variables
- ActiveRecord::RecordNotFound - Missing database records
- ArgumentError - Invalid method arguments
- SyntaxError - Ruby syntax issues
- Timeout errors - Database or network timeouts
- ZeroDivisionError - Division by zero
- And many more...
# .github/workflows/analyze-errors.yml
- name: Analyze production errors
run: |
debug_ai analyze logs/production.log --since "1 hour ago" --count 20#!/bin/bash
# monitor-errors.sh
echo "🔍 Checking for new errors in the last hour..."
debug_ai analyze log/production.log --since "$(date -v-1H '+%Y-%m-%d %H:%M')" --verbose# In your development environment
alias analyze-errors="debug_ai analyze log/development.log --count 5 --verbose"
alias monitor-logs="tail -f log/development.log | debug_ai analyze --live"- Local AI Models: Use Ollama or LM Studio to keep data on your machine
- Sensitive Data Filtering: Automatically filters passwords and tokens from logs
- No Data Storage: DebugAI doesn't store or transmit your logs beyond AI analysis
- Configurable: Full control over which AI provider to use
# Clone the repository
git clone https://github.com/aythamirm/debug_ai.git
cd debug_ai
# Install dependencies
bundle install
# Run tests
bundle exec rspec
# Test CLI locally
./exe/debug_ai analyze sample_rails.log- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -am 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
- Support for more log formats (Sidekiq, custom loggers)
- Search and filter commands
- JSON output format
- Configuration file support
- Web dashboard for log analysis
- Error pattern detection
- Integration with error tracking services
- Slack/Teams notifications
- Predictive error analysis
- Auto-fix suggestions with code generation
- Multi-application error correlation
- Performance impact analysis
The gem is available as open source under the terms of the MIT License.
- Inspired by the need for better debugging tools in the Ruby community
- Built with ❤️ for developers who want AI-assisted debugging
- Thanks to the Ruby community for continuous inspiration
- 🐛 Report Issues
- 💬 Discussions
Transform your debugging experience with AI! 🚀