Skip to content

About

This implementation automatically captures every error in your Laravel application and stores it in Elasticsearch, providing powerful search capabilities, real-time monitoring, and comprehensive error analytics that will transform how you debug and maintain your applications.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

3 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸš€ Laravel Error Logging with Elasticsearch

Laravel Elasticsearch PHP

Medium GitHub Stars

This implementation automatically captures every error in your Laravel application and stores it in Elasticsearch, providing powerful search capabilities, real-time monitoring, and comprehensive error analytics that will transform how you debug and maintain your applications.

Error Logging Dashboard

🏷️ This file is part of a series of articles on Medium

πŸ“‹ Table of Contents

✨ Features

πŸ” Comprehensive Error Tracking

  • 🎯 Automatic Exception Handling - Catches and processes all Laravel exceptions
  • 🏷️ Smart Error Categorization - Automatically tags errors by type, status, environment
  • πŸ“ Request Context Capture - Logs complete request information including headers, parameters, and user context
  • ⚑ Performance Metrics - Tracks response time and memory usage for each error

πŸ›‘οΈ Security-First Design

  • πŸ”’ Data Sanitization - Automatically removes sensitive data (passwords, tokens, API keys)
  • 🚫 Filtered Stack Traces - Removes sensitive function arguments from traces
  • πŸ›£οΈ Path Sanitization - Strips system paths from file references
  • πŸ›‘οΈ Header Protection - Redacts authentication and session headers

πŸ“Š Advanced Analytics

  • πŸ”Ž Real-time Search - Powerful Elasticsearch queries for error analysis
  • πŸ“ˆ Error Trends - Track error patterns over time
  • πŸ‘₯ User Impact Analysis - Identify which users are affected by errors
  • 🌍 Environment Comparison - Compare error rates across environments

🎯 Exception-Specific Handling

  • βœ… Authentication Exceptions - Secure handling of auth failures
  • βœ… Validation Exceptions - Detailed validation error tracking
  • βœ… Model Not Found Exceptions - Resource not found handling
  • βœ… Authorization Exceptions - Permission error management
  • βœ… HTTP Exceptions - HTTP status code tracking
  • βœ… Database Query Exceptions - SQL error monitoring
  • βœ… Custom Exception Support - Extensible for custom exceptions

πŸ”§ Prerequisites

  • 🐘 PHP 8.2 or higher
  • 🎯 Laravel 11.x (compatible with 10.x)
  • πŸ” Elasticsearch 8.x
  • πŸ“¦ Composer for dependency management

πŸš€ Installation

# Install Elasticsearch package
composer require elasticsearch/elasticsearch

2. **Laravel Configuration**
   - Add Elasticsearch package
   - Configure environment variables
   - Set up service provider

3. **Index Design**
   Create an Elasticsearch index with the following structure:
   ```json
   {
     "mappings": {
       "properties": {
         "type": { "type": "keyword" },
         "message": { "type": "text" },
         "status": { "type": "integer" },
         "uri": { "type": "keyword" },
         "method": { "type": "keyword" },
         "user": { "type": "object" },
         "ip": { "type": "ip" },
         "trace": { "type": "text" },
         "timestamp": { "type": "date" },
         "environment": { "type": "keyword" },
         "file": { "type": "keyword" },
         "line": { "type": "integer" },
         "request_data": { "type": "object" },
         "headers": { "type": "object" },
         "response_time": { "type": "float" },
         "memory_usage": { "type": "integer" },
         "tags": { "type": "keyword" }
       }
     }
   }

βš™οΈ Configuration

Environment Variables

ELASTICSEARCH_HOST=http://localhost:9200
ELASTICSEARCH_USERNAME=elastic
ELASTICSEARCH_PASSWORD=your_secure_password

Service Configuration

'elk' => [
    'host_ip' => env('ELASTICSEARCH_HOST', 'http://localhost:9200'),
    'username' => env('ELASTICSEARCH_USERNAME', 'elastic'),
    'password' => env('ELASTICSEARCH_PASSWORD', ''),
],

πŸ’» Usage Example

Sample Error Log Entry

{
   "_index": "error-logs",
   "_type": "_doc",
   "_id": "a7b8c9d0e1f2g3h4i5j6k7l8m9n0o1p2",
   "_score": 1.0,
   "_source": {
      "id": "d5e8a7b2c9f4e6a1b3d7f8e2c5a9b4d6",
      "type": "ValidationException",
      "message": "The email field is required.",
      "status": 422,
      "uri": "/api/users",
      "method": "POST",
      "user": {
         "id": "12345",
         "type": "sanctum_user",
         "name": "John Doe",
         "email": "john.doe@example.com"
      },
      "ip": "192.168.1.100",
      "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
      "trace": "[{\"file\":\"/app/Http/Controllers/UserController.php\",\"line\":45,\"function\":\"validate\",\"class\":\"Illuminate\\\\Http\\\\Request\"},{\"file\":\"/app/Http/Controllers/UserController.php\",\"line\":23,\"function\":\"store\",\"class\":\"App\\\\Http\\\\Controllers\\\\UserController\"},{\"file\":\"/vendor/laravel/framework/src/Illuminate/Routing/Controller.php\",\"line\":54,\"function\":\"callAction\"}]",
      "timestamp": "2025-06-02T14:32:15.847Z",
      "environment": "production",
      "file": "/app/Http/Requests/CreateUserRequest.php",
      "line": 28,
      "context": {
         "request_id": "req_9f8e7d6c5b4a3210fedcba0987654321",
         "session_id": "sess_abcd1234efgh5678ijkl9012mnop3456",
         "correlation_id": "corr_xyz789abc123def456ghi789jkl012"
      },
      "request_data": {
         "input": {
            "name": "John Doe",
            "phone": "+1234567890",
            "password": "[REDACTED]"
         },
         "query": {
            "source": "mobile_app",
            "version": "1.2.3"
         },
         "files": []
      },
      "headers": {
         "host": ["api.example.com"],
         "user-agent": ["Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"],
         "accept": ["application/json"],
         "content-type": ["application/json"],
         "authorization": ["[REDACTED]"],
         "x-requested-with": ["XMLHttpRequest"],
         "x-api-version": ["v1"],
         "cookie": ["[REDACTED]"]
      },
      "response_time": 245.67,
      "memory_usage": 8388608,
      "tags": [
         "production",
         "validationexception",
         "post",
         "client_error",
         "api",
         "authenticated"
      ]
   }
}

Best Practices

  1. Security
    • Never log sensitive data
    • Implement proper data sanitization
    • Use secure authentication
    • Limit stack trace information
    • Filter request data

⭐ Best Practices

πŸ”’ Security

  • 🚫 Never log sensitive data
  • πŸ›‘οΈ Implement proper data sanitization
  • πŸ” Use secure authentication
  • πŸ“ Limit stack trace information
  • 🧹 Filter request data

⚑ Performance

  • πŸ“Š Implement proper indexing
  • πŸ“¦ Use bulk operations when possible
  • πŸ”„ Implement connection pooling
  • ⚠️ Add proper error handling
  • πŸ”„ Include fallback mechanisms

πŸ”§ Maintenance

  • πŸ“… Implement index lifecycle management
  • πŸ“Š Set up proper monitoring
  • πŸ’Ύ Create backup strategies
  • πŸ“ Document error patterns
  • πŸ” Regular security audits

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

⭐ Star This Repository ⭐

Your support helps us improve and maintain this project!

GitHub Stars

About

This implementation automatically captures every error in your Laravel application and stores it in Elasticsearch, providing powerful search capabilities, real-time monitoring, and comprehensive error analytics that will transform how you debug and maintain your applications.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages