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

Guzzle Log Middleware Laravel Package

rtheunissen/guzzle-log-middleware

Lightweight Guzzle middleware for logging HTTP requests and responses. Capture method, URL, headers, body, status and timing, and route logs through PSR-3/Monolog with configurable formats, levels, and filtering—ideal for debugging and auditing API traffic.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require rtheunissen/guzzle-log-middleware
    
  2. Basic Usage Import the middleware and attach it to your Guzzle client:

    use RTheunissen\GuzzleLogMiddleware\GuzzleLogMiddleware;
    
    $client = new \GuzzleHttp\Client([
        'middleware' => [
            new GuzzleLogMiddleware(),
        ],
    ]);
    
  3. First Use Case Log a simple GET request to debug API responses:

    $response = $client->get('https://api.example.com/users');
    // Check Laravel logs for request/response details
    

Implementation Patterns

Common Workflows

  1. Logging All Requests Attach the middleware globally in Laravel’s AppServiceProvider:

    public function boot()
    {
        $this->app->extend('http-client', function ($client) {
            $client->getEmitter()->attach(
                new GuzzleLogMiddleware()
            );
            return $client;
        });
    }
    
  2. Conditional Logging Use middleware options to filter logs (e.g., by HTTP method or URL):

    $middleware = new GuzzleLogMiddleware([
        'log_request' => true,
        'log_response' => true,
        'log_body' => true,
        'exclude' => ['/health', '/ping'],
    ]);
    
  3. Custom Logging Channels Override the default logger (e.g., Monolog) by binding a custom handler:

    $client->getEmitter()->attach(
        new GuzzleLogMiddleware(['logger' => app('custom-logger')])
    );
    
  4. Logging in API Services Wrap Guzzle calls in a service class:

    class ApiService {
        protected $client;
    
        public function __construct(\GuzzleHttp\Client $client)
        {
            $this->client = $client->withMiddleware(
                new GuzzleLogMiddleware()
            );
        }
    
        public function fetchUsers()
        {
            return $this->client->get('/users')->getBody();
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Performance Overhead

    • Logging every request/response adds latency. Use exclude patterns for non-critical endpoints.
    • Disable logging in production unless debugging:
      $middleware = new GuzzleLogMiddleware(['enabled' => env('APP_DEBUG')]);
      
  2. Sensitive Data Leaks

    • Never log raw request/response bodies containing passwords, tokens, or PII. Use:
      $middleware = new GuzzleLogMiddleware(['log_body' => false]);
      
    • For APIs, redact sensitive fields post-logging (e.g., using Laravel’s Str::mask()).
  3. Log Format Inconsistencies

    • The middleware uses Monolog’s default format. Customize via Laravel’s log config or override the logger:
      $middleware = new GuzzleLogMiddleware([
          'logger' => \Monolog\Logger::create('guzzle', [
              new \Monolog\Formatter\LineFormatter(
                  "[%datetime%] %level_name%: %message%\n%context%\n"
              )
          ])
      ]);
      
  4. Middleware Order Matters

    • Place GuzzleLogMiddleware after error-handling middleware to avoid masking exceptions:
      $stack = \GuzzleHttp\HandlerStack::create();
      $stack->push(\GuzzleHttp\Middleware::retry(), 'retry');
      $stack->push(new GuzzleLogMiddleware(), 'log'); // Log after retries
      

Debugging Tips

  1. Verify Middleware Attachment Check if the middleware is active by inspecting the HandlerStack:

    dd($client->getConfig('handler')->getMiddleware());
    
  2. Log Levels Adjust Monolog’s log level (e.g., debug for Guzzle logs):

    'channels' => [
        'guzzle' => [
            'driver' => 'single',
            'level' => 'debug',
        ],
    ],
    
  3. Exclude Specific Requests Use regex in exclude to skip internal calls:

    $middleware = new GuzzleLogMiddleware([
        'exclude' => ['/internal/.*', 'localhost']
    ]);
    
  4. Custom Context Data Add request IDs or user context:

    $request = $client->get('...', [
        'on_stats' => function ($result) {
            $result['request_id'] = Str::uuid()->toString();
        }
    ]);
    

Extension Points

  1. Pre/Post-Processing Extend the middleware by subclassing:

    class CustomGuzzleLogMiddleware extends GuzzleLogMiddleware {
        public function __construct(array $options = [])
        {
            parent::__construct($options);
        }
    
        protected function logRequest($request, $options)
        {
            // Add custom logic (e.g., enrich context)
            $options['context']['custom_field'] = 'value';
            parent::logRequest($request, $options);
        }
    }
    
  2. Integrate with Laravel Debugbar Use barryvdh/laravel-debugbar to display Guzzle logs in the debug panel:

    $middleware = new GuzzleLogMiddleware([
        'logger' => \Debugbar::getMessageCollector('guzzle')
    ]);
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky