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

Technical Evaluation

Architecture Fit

  • HTTP Client Layer Alignment: The package is a Guzzle middleware, making it a natural fit for Laravel applications that rely on Guzzle (e.g., via GuzzleHttp\Client or Laravel’s HTTP client facade). It integrates seamlessly into the request/response lifecycle without disrupting core Laravel architecture.
  • Observability-First Design: Aligns with modern Laravel practices (e.g., logging, monitoring) by providing structured request/response logging out-of-the-box. Complements tools like Laravel’s Log facade, Monolog, or third-party observability stacks (e.g., Sentry, Datadog).
  • Extensibility: Middleware-based design allows for custom logging formats (e.g., JSON, structured logs) or conditional logging (e.g., only for failed requests). Can be extended via Guzzle’s middleware stack or Laravel’s service container.

Integration Feasibility

  • Low Friction: Guzzle is Laravel’s default HTTP client (since v7+), and this middleware requires zero Laravel-specific modifications. Works with:
    • Laravel’s HTTP client facade (Http::withOptions()).
    • Direct Guzzle client instances (e.g., in services, jobs, or console commands).
  • Configuration Flexibility:
    • Can be added globally (e.g., in AppServiceProvider) or per-request (e.g., in a service method).
    • Supports custom log handlers (e.g., write to a file, database, or external service).
  • Backward/Forward Compatibility:
    • Guzzle 6: Laravel 7+ uses Guzzle 6/7; this package targets Guzzle 6, so minor version bumps may be needed if using Guzzle 7+ (check Guzzle’s BC breaks).
    • PHP 7.2+: No Laravel-specific PHP version constraints, but aligns with Laravel’s current support (PHP 8.0+).

Technical Risk

Risk Area Assessment Mitigation Strategy
Performance Overhead Logging adds I/O latency. Structured logs (e.g., JSON) may increase payload size. Use async logging (e.g., Monolog handlers) or sample logs in production.
Log Volume High-traffic apps may generate excessive logs. Implement log filtering (e.g., skip 200 OK responses) or rate-limiting.
Guzzle Version Mismatch Guzzle 6 vs. 7+ may have breaking changes. Test with Laravel’s default Guzzle version; use guzzlehttp/guzzle:^6.5 in composer.json.
Log Format Inconsistency Custom formats may break downstream tools (e.g., ELK, Splunk). Standardize on JSON logs with consistent fields (e.g., timestamp, method, url, status).
Middleware Order Incorrect placement in Guzzle’s stack may log incomplete data. Place after auth/retries but before error handling (e.g., Http::withMiddleware()).

Key Questions

  1. Logging Destination:

    • Will logs go to Laravel’s default storage/logs/laravel.log, a dedicated file, or an external system (e.g., ELK, Datadog)?
    • Impact: Affects configuration complexity and performance.
  2. Log Granularity:

    • Should all requests be logged, or only failures/errors? Should payloads (body) be logged for POST/PUT?
    • Impact: Balances observability vs. noise/privacy (e.g., avoid logging sensitive data like passwords).
  3. Guzzle Usage Pattern:

    • Is Guzzle used only via Laravel’s HTTP client, or also directly in services/jobs?
    • Impact: Determines whether middleware needs to be applied globally or selectively.
  4. Existing Observability Stack:

    • Does the team use tools like Sentry, New Relic, or custom metrics? Can this package’s logs be enriched/forwarded?
    • Impact: May require additional parsing/formatting layers.
  5. Performance SLAs:

    • Are there strict latency requirements for HTTP calls? How does logging overhead compare to baselines?
    • Impact: May necessitate async logging or sampling.

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • Native Integration: Works with Laravel’s HTTP client (Http::withMiddleware()) and Guzzle’s Client directly.
    • Service Container: Middleware can be bound to the container for reuse (e.g., in AppServiceProvider).
    • Logging Stack: Integrates with Laravel’s Log facade or Monolog handlers (e.g., SingleLineFormatter for JSON).
  • Third-Party Tools:
    • Monitoring: Logs can be forwarded to tools like Sentry (via Sentry\Laravel\Integration), Datadog, or ELK.
    • APM: Complements tools like New Relic or Laravel Telescope for end-to-end tracing.

Migration Path

  1. Assessment Phase:
    • Audit existing HTTP clients (Guzzle usage in services, jobs, controllers).
    • Identify critical paths (e.g., API calls to payment gateways, third-party services).
  2. Pilot Integration:
    • Start with non-critical endpoints (e.g., internal APIs, health checks).
    • Use Http::withMiddleware() to test logging without disrupting production.
  3. Gradual Rollout:
    • Phase 1: Log requests/responses for a subset of services (e.g., auth, orders).
    • Phase 2: Extend to all HTTP clients; adjust log format/volume based on feedback.
    • Phase 3: Integrate with monitoring tools (e.g., parse logs in ELK for dashboards).
  4. Fallback Plan:
    • If performance issues arise, implement log sampling (e.g., log 1% of requests) or async logging.

Compatibility

Component Compatibility Notes
Laravel Version Works with Laravel 7+ (Guzzle 6/7). Test with Laravel 8/9 for any Guzzle 7+ changes.
Guzzle Version Targets Guzzle 6; may need adapter for Guzzle 7+ (e.g., guzzlehttp/guzzle:^6.5).
PHP Version PHP 7.2+ (no Laravel-specific constraints).
Logging Libraries Compatible with Monolog, Laravel’s Log facade, or custom PSR-3 loggers.
Async Queues Safe for use in Laravel queues/jobs (no blocking I/O if logs are async).

Sequencing

  1. Middleware Registration:
    • Global: Register in AppServiceProvider::boot():
      use Rtheunissen\GuzzleLogMiddleware\LogMiddleware;
      Http::macro('withLogging', function () {
          return $this->withMiddleware(new LogMiddleware());
      });
      
    • Per-Request: Apply selectively:
      $response = Http::withLogging()->get('https://api.example.com');
      
  2. Log Configuration:
    • Configure log format (e.g., JSON) and destination (e.g., Monolog handler):
      $middleware = new LogMiddleware(new \Monolog\Logger('guzzle'), new \Monolog\Handler\StreamHandler(storage_path('logs/guzzle.log')));
      
  3. Testing:
    • Unit test middleware with mock Guzzle clients.
    • Integration test with real HTTP calls (e.g., in phpunit.xml):
      <env name="GUZZLE_LOG_ENABLED" value="true"/>
      
  4. Monitoring Setup:
    • Parse logs in ELK/Splunk or forward to APM tools (e.g., New Relic’s log ingestion).

Operational Impact

Maintenance

  • Configuration Drift:
    • Risk: Log formats/destinations may diverge across environments (dev/staging/prod).
    • Mitigation: Use Laravel’s config/guzzle.php or environment variables for log settings.
  • Middleware Updates:
    • Risk: Package updates may introduce breaking changes (e.g., Guzzle 7+).
    • Mitigation: Pin Guzzle version in composer.json and test updates in staging.
  • Log Retention:
    • Risk: Unbounded log growth in storage.
    • Mitigation: Implement log rotation (e.g., Monolog’s RotatingFileHandler) or cloud storage (e.g., S3).

Support

  • Debugging Workflow:
    • Pros: Rich request/response logs simplify debugging (e.g., API failures, timeouts).
    • Cons: Over-reliance on logs may obscure other issues (e.g., race conditions).
  • On-Call Impact:
    • Positive: Logs reduce MTTR for HTTP-related incidents (e
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