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

Log Laravel Package

guzzle/log

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Require the package via Composer (note: this is for Guzzle 3.x, which is deprecated):

    composer require guzzle/log
    

    For Laravel projects, prioritize Guzzle 6/7.x and use alternatives like guzzlehttp/logger-middleware.

  2. Basic Setup Integrate with Guzzle 3.x’s client by passing a PSR-3 logger (e.g., Monolog):

    use Guzzle3\Log\LogAdapter;
    use Monolog\Logger;
    use Monolog\Handler\StreamHandler;
    
    $logger = new Logger('guzzle');
    $logger->pushHandler(new StreamHandler('php://stdout', Logger::DEBUG));
    
    $logAdapter = new LogAdapter($logger);
    $client = new Guzzle3\Client(['logger' => $logAdapter]);
    
  3. First Use Case Log HTTP requests/responses for debugging:

    $response = $client->get('https://api.example.com/data');
    // Logs appear in stdout with request/response details.
    

Implementation Patterns

Core Workflows

  1. Laravel Integration Use Laravel’s Monolog instance with the adapter:

    $client = new Guzzle3\Client([
        'logger' => new LogAdapter(app('log')->getMonolog())
    ]);
    
  2. Conditional Logging Disable logging in production by adjusting the logger level:

    $logger->setLevel(env('APP_DEBUG') ? Logger::DEBUG : Logger::ERROR);
    
  3. Custom Log Context Extend LogAdapter to add metadata (e.g., request IDs):

    class CustomLogAdapter extends LogAdapter {
        public function log($level, $message, array $context = []) {
            $context['request_id'] = request()->header('X-Request-ID');
            parent::log($level, $message, $context);
        }
    }
    
  4. Log to External Services Route logs to Sentry or ELK via Monolog handlers:

    $logger->pushHandler(new \Sentry\Monolog\Handler(
        Sentry::getClient(),
        Sentry\State\ScopeCallback::LEVEL_ERROR
    ));
    

Laravel-Specific Tips

  • Service Provider Binding Bind the Guzzle client with logging in AppServiceProvider:

    public function register() {
        $this->app->singleton('guzzle.client', function ($app) {
            $logger = $app['log']->getMonolog();
            return new Guzzle3\Client([
                'logger' => new LogAdapter($logger)
            ]);
        });
    }
    
  • Queue Job Logging Log HTTP calls in queued jobs:

    use Illuminate\Bus\Queueable;
    use Illuminate\Queue\SerializesModels;
    
    class ProcessPaymentJob implements Queueable, SerializesModels {
        public function handle() {
            $client = app('guzzle.client');
            $response = $client->post('https://payment-gateway.com/charge', [...]);
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Guzzle 3.x Deprecation

    • Risk: Guzzle 3.x is end-of-life (abandoned since 2015). Avoid in new projects.
    • Fix: Migrate to Guzzle 7.x + guzzlehttp/logger-middleware or Laravel’s HttpClient.
  2. Log Bloat

    • Issue: Raw request/response bodies (e.g., JSON/XML) can bloat logs.
    • Fix: Use Monolog processors to truncate or redact data:
      $logger->pushProcessor(function (array $record) {
          $record['context']['body'] = substr($record['context']['body'], 0, 200) . '...';
          return $record;
      });
      
  3. Sensitive Data Leaks

    • Issue: Logs may expose tokens, passwords, or PII.
    • Fix: Redact sensitive fields in the adapter:
      class SecureLogAdapter extends LogAdapter {
          public function log($level, $message, array $context = []) {
              unset($context['request']['headers']['authorization']);
              parent::log($level, $message, $context);
          }
      }
      
  4. Performance in High-Load Environments

    • Issue: Logging every request adds overhead in microservices.
    • Fix: Sample logs or use async handlers:
      $logger->pushHandler(new \Monolog\Handler\AsyncHandler(
          new \Monolog\Handler\StreamHandler('php://stderr')
      ));
      

Debugging Tips

  • Verify Logger Integration Check if logs appear by testing a simple request:

    $client->get('https://httpbin.org/get'); // Should log request/response.
    
  • Check Monolog Configuration Ensure Laravel’s logging.php routes Guzzle logs correctly:

    'channels' => [
        'guzzle' => [
            'driver' => 'single',
            'path' => storage_path('logs/guzzle.log'),
            'level' => 'debug',
        ],
    ],
    
  • Handle Binary Data Guzzle 3.x may log binary payloads as base64. Use a custom adapter to decode:

    class BinaryLogAdapter extends LogAdapter {
        public function log($level, $message, array $context = []) {
            if (isset($context['request']['body'])) {
                $context['request']['body'] = base64_decode($context['request']['body']);
            }
            parent::log($level, $message, $context);
        }
    }
    

Extension Points

  1. Custom Log Formatters Override LogAdapter to format logs as JSON:

    class JsonLogAdapter extends LogAdapter {
        public function log($level, $message, array $context = []) {
            $log = [
                'timestamp' => date('c'),
                'level' => $level,
                'message' => $message,
                'context' => $context,
            ];
            parent::log($level, json_encode($log), []);
        }
    }
    
  2. Dynamic Logger Levels Adjust log levels based on environment:

    $logAdapter = new LogAdapter($logger);
    $logAdapter->setLevel(env('GUZZLE_LOG_LEVEL', Logger::WARNING));
    
  3. Integration with Laravel Events Trigger events on log entries:

    $logger->pushHandler(new class extends AbstractProcessingHandler {
        protected function processRecord($record) {
            if ($record['level'] === Logger::ERROR) {
                event(new GuzzleLogError($record));
            }
        }
    });
    

Laravel-Specific Quirks

  • Queue Job Logging Logs from queued jobs may appear out of order. Use request_id for correlation:

    $logger->pushProcessor(function ($record) {
        $record['extra']['request_id'] = Str::uuid()->toString();
        return $record;
    });
    
  • Horizon Queue Monitoring Combine with Laravel Horizon to track failed jobs with logged HTTP errors.

  • Telescope Integration Forward Guzzle logs to Laravel Telescope for real-time inspection:

    $logger->pushHandler(new \Laravel\Telescope\Handlers\LogHandler());
    
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.
babenkoivan/elastic-client
innmind/static-analysis
innmind/coding-standard
datacore/hub-sdk
alengo/sulu-http-cache-bundle
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php