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

Technical Evaluation

Architecture Fit

  • Middleware-Based Design: The package integrates seamlessly into Laravel’s middleware stack, aligning with Laravel’s native request/response lifecycle. This ensures minimal disruption to existing architecture while providing a non-intrusive logging layer.
  • Safety Net Use Case: Ideal for applications where request persistence is critical (e.g., lead forms, payments, or high-stakes user actions). The package’s focus on preserving raw request data during failures complements Laravel’s built-in logging but adds a specialized layer for debugging or auditing.
  • Extensibility: The package allows customization of log format, storage (e.g., database, external services), and middleware configuration, making it adaptable to varying logging needs.

Integration Feasibility

  • Low Friction: Requires only middleware registration ($middlewareGroups or $middleware in app/Http/Kernel.php) and optional configuration (e.g., log format, excluded routes). No database migrations or complex setup.
  • Laravel Native: Leverages Laravel’s logging system (Monolog), ensuring compatibility with existing log handlers (e.g., single, daily, or custom drivers like Slack, Sentry).
  • Performance Impact: Minimal overhead during normal operation, but logging all requests may introduce latency in high-throughput systems. Benchmarking recommended for production environments.

Technical Risk

  • Log Volume: Unfiltered logging of all requests could lead to storage bloat or performance degradation. Requires upfront planning for log retention (e.g., log rotation, external storage).
  • Sensitive Data Exposure: Raw request logging may include PII or sensitive headers (e.g., Authorization). Mitigation: Use the package’s excludeHeaders config or pre-process requests.
  • Middleware Ordering: Incorrect placement in the middleware stack (e.g., after authentication) could log incomplete request data. Test with critical paths.
  • Dependency Stability: Relies on Laravel core and Monolog. Risk is low given Laravel’s stability, but version compatibility must be validated during adoption.

Key Questions

  1. Logging Scope: Should all requests be logged, or only specific routes/endpoints? How will this be configured?
  2. Storage Strategy: Where will logs be stored (e.g., filesystem, database, external service)? How will retention/purging be managed?
  3. Performance Baseline: What is the acceptable latency impact of logging? Should sampling or filtering be implemented?
  4. Sensitive Data Handling: Are there headers/parameters that must be redacted or excluded from logs?
  5. Alerting/Monitoring: Will logs trigger alerts (e.g., failed requests)? If so, how will they integrate with existing monitoring (e.g., Sentry, Datadog)?
  6. Compliance: Does logging align with data protection regulations (e.g., GDPR)? Are logs encrypted at rest?
  7. Testing Coverage: How will the logging layer be validated in CI/CD (e.g., log format, failure scenarios)?

Integration Approach

Stack Fit

  • Laravel Ecosystem: Perfect fit for Laravel applications, especially those using Monolog for logging. No additional infrastructure required beyond Laravel’s native stack.
  • Compatibility:
    • PHP Version: Supports PHP 8.0+ (aligns with Laravel 9+).
    • Laravel Version: Tested with Laravel 9.x/10.x (check composer.json constraints).
    • Monolog: Works with any Monolog handler (e.g., tap, syslog, slack).
    • Middleware: Compatible with Laravel’s middleware stack, including third-party middleware (e.g., CORS, auth).
  • Non-Invasive: Does not require changes to routes, controllers, or services. Logs are captured transparently.

Migration Path

  1. Evaluation Phase:
    • Install the package in a staging environment: composer require spatie/laravel-http-logger.
    • Configure via .env or config/http-logger.php (e.g., log format, excluded routes).
    • Test with a subset of critical routes to validate log output and performance.
  2. Pilot Deployment:
    • Enable logging for non-production traffic (e.g., /api/leads).
    • Monitor log volume, storage, and impact on response times.
  3. Full Rollout:
    • Gradually enable for all routes or specific middleware groups.
    • Update monitoring/alerting to include HTTP log analysis.
  4. Post-Deployment:
    • Implement log rotation/purging (e.g., Laravel Forge, AWS S3 lifecycle policies).
    • Document logging strategy for on-call teams.

Compatibility

  • Existing Middleware: Works alongside other middleware (e.g., auth, CORS) but must be ordered correctly (e.g., log before auth to capture raw requests).
  • Custom Logging: Can be extended to include additional context (e.g., user ID, request ID) via the LogFormat class.
  • Non-Laravel Components: If using non-Laravel HTTP clients (e.g., Guzzle), this package won’t apply. Focuses solely on Laravel’s request lifecycle.

Sequencing

  1. Prerequisites:
    • Ensure Laravel’s logging is configured (e.g., LOG_CHANNEL in .env).
    • Validate Monolog handlers meet storage/reliability requirements.
  2. Middleware Registration:
    • Add to $middlewareGroups['web'] or $middleware in app/Http/Kernel.php:
      \Spatie\HttpLogging\Middleware\LogHttpRequests::class,
      
  3. Configuration:
    • Customize config/http-logger.php (e.g., log_format, exclude_headers).
    • Example: Exclude sensitive headers:
      'exclude_headers' => ['authorization', 'cookie'],
      
  4. Testing:
    • Verify logs appear in storage/logs/laravel.log (or configured handler).
    • Test failure scenarios (e.g., 500 errors) to confirm request persistence.
  5. Monitoring:
    • Set up alerts for log file size or error patterns (e.g., LogHttpRequests exceptions).

Operational Impact

Maintenance

  • Configuration Drift: Minimal risk if configuration is version-controlled (e.g., config/http-logger.php in Git).
  • Package Updates: Regular updates from Spatie are low-risk (MIT license, active maintenance). Monitor Laravel version compatibility.
  • Log Management:
    • Rotation: Leverage Laravel’s log rotation (e.g., daily channel) or external tools (e.g., AWS CloudWatch, Papertrail).
    • Retention: Define policies for log archival/deletion (e.g., 30-day retention for production).
  • Dependency Updates: Monitor for breaking changes in Monolog or Laravel core.

Support

  • Debugging: Provides a safety net for debugging failed requests (e.g., POST data, headers). Reduces reliance on browser dev tools for critical issues.
  • Incident Response:
    • Logs can be queried during post-mortems (e.g., "Why did this lead form fail?").
    • Integrate with error trackers (e.g., Sentry) by forwarding logs via a custom Monolog handler.
  • Documentation: Spatie’s package includes clear README and changelog. Community support via GitHub issues.
  • Training: Minimal ramp-up for developers; primarily a "set and forget" tool unless customizations are needed.

Scaling

  • Performance:
    • High Traffic: Logging all requests may impact performance. Mitigate with:
      • Sampling: Log only a percentage of requests (e.g., via LogHttpRequests::only()).
      • Async Logging: Use Monolog’s async handlers (e.g., async channel) to offload I/O.
      • External Storage: Stream logs to a service like Loki or ELK stack.
    • Benchmark: Test with production-like traffic to measure latency impact.
  • Storage:
    • Filesystem: Default storage may not scale for high-volume logs. Consider:
      • Database: Store logs in a table (e.g., http_logs) with TTL for retention.
      • External: Ship logs to S3, GCS, or a log management tool.
    • Cold Storage: Archive old logs to cheaper storage (e.g., S3 Glacier).

Failure Modes

Failure Scenario Impact Mitigation
Log file corruption Lost request data Use filesystem drivers with checksums or switch to database storage.
Storage full (e.g., disk) Logging failures, app crashes Set up alerts for disk space; implement log rotation/purging.
High log volume Degraded performance Sample logs, use async handlers, or filter routes.
Sensitive data leaked Compliance violations Exclude headers/parameters; redact PII in logs.
Middleware misconfiguration Incomplete/inconsistent logs Test with critical paths; validate middleware order.
Monolog handler failure Logs not written Use redundant handlers (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.
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