Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Http Logger Laravel Package

spatie/laravel-http-logger

Laravel middleware that logs incoming HTTP requests (payload, headers, etc.) to your configured log/channel, creating a safety net for critical form submissions and debugging. Includes toggleable enable flag plus customizable log profile and writer.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/laravel-http-logger
    

    Publish the config file:

    php artisan vendor:publish --provider="Spatie\HttpLogger\HttpLoggerServiceProvider" --tag="config"
    
  2. Register Middleware: Add the middleware to your app/Http/Kernel.php under $middleware or $middlewareGroups (e.g., web):

    \Spatie\HttpLogger\HttpLoggerMiddleware::class,
    
  3. First Use Case: Log a critical form submission (e.g., a lead capture form) by ensuring the middleware is applied to the route handling it. The package will automatically log:

    • Request method (GET, POST, etc.)
    • URL
    • Headers
    • Payload (for non-GET requests)
    • IP address
    • User agent

    Example route:

    Route::post('/leads', [LeadController::class, 'store'])->middleware('web');
    

Implementation Patterns

Core Workflows

  1. Selective Logging: Use the log config option to restrict logging to specific routes or HTTP methods:

    'log' => [
        'methods' => ['POST', 'PUT', 'PATCH', 'DELETE'],
        'paths' => ['/leads', '/payments/*'],
    ],
    

    This avoids cluttering logs with GET requests or non-critical endpoints.

  2. Excluding Sensitive Data: Sanitize payloads by defining blacklisted keys in config/http-logger.php:

    'blacklist' => [
        'password',
        'credit_card_number',
        'api_key',
    ],
    

    Use regex patterns for dynamic exclusion:

    'blacklist' => [
        '/^password.*$/i',
    ],
    
  3. Custom Log Channels: Direct logs to a dedicated channel (e.g., single or daily) by extending the config:

    'channel' => env('HTTP_LOG_CHANNEL', 'stack'),
    

    Configure the channel in config/logging.php.

  4. Integration with Monitoring: Pipe logs to external services (e.g., Sentry, Datadog) by extending the logger:

    use Spatie\HttpLogger\Loggers\Logger;
    
    class CustomLogger extends Logger
    {
        public function log(array $data)
        {
            parent::log($data);
            // Send to external service
            Sentry::captureMessage(json_encode($data));
        }
    }
    

    Bind the custom logger in AppServiceProvider:

    $this->app->bind(\Spatie\HttpLogger\Loggers\Logger::class, CustomLogger::class);
    
  5. Conditional Logging: Dynamically enable/disable logging based on environment or user roles:

    if (app()->environment('production') && auth()->check()) {
        config(['http-logger.log' => true]);
    }
    

Gotchas and Tips

Pitfalls

  1. Performance Overhead:

    • Logging every request (especially with large payloads) can impact performance. Use the log config to restrict scope.
    • Tip: Exclude API routes or health checks from logging:
      'log' => [
          'exclude' => ['/api/*', '/health'],
      ],
      
  2. Payload Size Limits:

    • Large payloads (e.g., file uploads) may exceed Laravel’s default log line length (~4KB). Adjust config/logging.php:
      'channels' => [
          'stack' => [
              'driver' => 'stack',
              'channels' => ['single'],
              'ignore_exceptions' => false,
              'max_files' => 5,
              'max_size' => 1024, // Increase size in KB
          ],
      ],
      
  3. Middleware Order:

    • Place HttpLoggerMiddleware after authentication middleware to log user context (e.g., auth:api). Example:
      $middlewareGroups['api'] = [
          \App\Http\Middleware\Authenticate::class,
          \Spatie\HttpLogger\HttpLoggerMiddleware::class,
      ];
      
  4. Sensitive Data Leaks:

    • Gotcha: Forgetting to blacklist fields like password or token can expose PII.
    • Tip: Use a regex blacklist for dynamic fields (e.g., ^/secret_.*$/i).
  5. Log Rotation:

    • Ensure log rotation is configured to avoid disk space issues. Example for single channel:
      'single' => [
          'driver' => 'single',
          'path' => storage_path('logs/http/http.log'),
          'level' => 'debug',
      ],
      

Debugging

  1. Verify Logging: Check if logs appear in storage/logs/laravel.log (or your configured channel). Use:

    tail -f storage/logs/laravel.log | grep "HTTP_LOGGER"
    
  2. Middleware Not Triggering:

    • Ensure the middleware is registered in Kernel.php.
    • Debug: Add a temporary log in the middleware’s handle method to confirm execution:
      \Log::debug('HTTP Logger triggered', ['request' => $request->all()]);
      
  3. Blacklist Not Working:

    • Test blacklist patterns with regex tools (e.g., regex101.com).
    • Tip: Use dd($request->all()) in a route to verify payload structure before logging.

Extension Points

  1. Custom Log Format: Extend the logger to modify the log structure:

    class CustomLogger extends Logger
    {
        protected function prepareLogData(Request $request): array
        {
            $data = parent::prepareLogData($request);
            $data['custom_field'] = 'value';
            return $data;
        }
    }
    
  2. Database Logging: Store logs in a database table by creating a custom logger:

    class DatabaseLogger extends Logger
    {
        public function log(array $data)
        {
            \App\Models\HttpLog::create($data);
        }
    }
    
  3. Rate Limiting: Combine with throttle middleware to log excessive requests:

    Route::middleware(['throttle:10,1', 'http-logger'])->group(function () {
        // Rate-limited routes
    });
    
  4. Webhook Notifications: Trigger a webhook on critical logs (e.g., failed payments):

    class CriticalLogger extends Logger
    {
        public function log(array $data)
        {
            parent::log($data);
            if (in_array($data['method'], ['POST']) && str_contains($data['path'], '/payments')) {
                Http::post('https://your-webhook-url', ['event' => 'payment_attempt', 'data' => $data]);
            }
        }
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport