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

Symfony Request Logger Laravel Package

dittto/symfony-request-logger

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. Installation:

    composer require dittto/symfony-request-logger
    

    (Note: This package is Symfony-focused, but Laravel can adapt it via middleware or service providers.)

  2. Basic Configuration:

    • Register the logger in config/app.php under providers:
      Dittto\RequestLogger\RequestLoggerServiceProvider::class,
      
    • Publish the config (if available) or manually define Guzzle middleware in AppServiceProvider@boot():
      $this->app->singleton('http_client.handlerstack', function () {
          $stack = HandlerStack::create();
          $stack->push(new \Dittto\RequestLogger\Middleware\RequestLoggerMiddleware());
          return $stack;
      });
      
  3. First Use Case:

    • Inject the Guzzle client into a controller/service:
      use GuzzleHttp\Client;
      
      public function fetchExternalData(Client $client) {
          $response = $client->get('https://api.example.com/data');
          // Logs will auto-capture timing, status, and payload.
      }
      
    • Debug Output: Enable Laravel’s debug mode (APP_DEBUG=true) to see JSON logs appended to responses.

Implementation Patterns

Workflow: Logging External API Calls

  1. Middleware Integration:

    • Wrap Guzzle calls in the logger’s middleware (as shown above). The package tracks:
      • Request URL, method, headers, and payload.
      • Response status, duration, and body (if small).
    • Laravel Tip: Use Http::withOptions(['handler' => $stack]) for custom clients.
  2. Log Output:

    • Monolog: Logs are written to Monolog channels (configure via dittto_request_logger config).
    • Debug Mode: JSON logs appear in Laravel’s debug bar or response headers (e.g., X-Request-Logs).
  3. Conditional Logging:

    • Exclude sensitive endpoints (e.g., payment gateways) by filtering middleware:
      $stack->push(new RequestLoggerMiddleware(), 'priority', function ($request) {
          return !str_contains($request->getUri(), ['/payments', '/tokens']);
      });
      
  4. Performance Monitoring:

    • Correlate logs with Laravel’s query/loggers using X-Request-ID headers.

Integration Tips

  • Laravel HTTP Client: Replace Guzzle’s Client with Laravel’s Http facade (v8+):
    $stack = HandlerStack::create();
    $stack->push(new RequestLoggerMiddleware());
    $client = new Client(['handler' => $stack]);
    Http::macro('withLogger', fn () => Http::withOptions(['handler' => $stack]));
    
  • Queue Failed Requests: Extend the middleware to log failed requests to a queue for retries:
    if ($response->getStatusCode() >= 400) {
        dispatch(new LogFailedRequest($request, $response));
    }
    

Gotchas and Tips

Pitfalls

  1. Debug Mode Dependency:

    • JSON logs only appear in debug mode. For production, rely solely on Monolog.
    • Fix: Extend the middleware to log to Monolog unconditionally.
  2. Payload Size Limits:

    • Large responses may be truncated. Configure max_body_size in the middleware:
      # config/packages/dittto_request_logger.yaml
      dittto_request_logger:
          max_body_size: 1024 # bytes
      
  3. Middleware Order:

    • Place RequestLoggerMiddleware after auth/retries but before error handlers to capture full request/response cycles.
  4. Symfony-Specific Assumptions:

    • The package assumes Symfony’s Request object. In Laravel, adapt the middleware to use Psr\Http\Message\RequestInterface:
      use Psr\Http\Message\RequestInterface;
      $request = $this->getRequest(); // Laravel's Request or Psr7 Request.
      

Debugging

  • Log Format: Inspect Monolog’s request_logger channel for raw data:
    \Log::channel('request_logger')->debug('Custom log');
    
  • Middleware Debugging: Temporarily add a tap to the middleware to inspect requests:
    $stack->push(new RequestLoggerMiddleware(), 'debug', function ($request) {
        \Log::debug('Request:', [$request->getUri(), $request->getHeaders()]);
    });
    

Extension Points

  1. Custom Log Fields:

    • Override the logger’s logRequest method to add metadata (e.g., user ID):
      $logger->logRequest($request, $response, ['user_id' => auth()->id()]);
      
  2. Slack/Alerting:

    • Subscribe to the request_logger Monolog channel to trigger alerts:
      \Log::extend('slack', function () {
          return new SlackHandler('webhook_url');
      });
      
  3. Laravel Horizon:

    • Process logs asynchronously by publishing them to a queue:
      dispatch(new ProcessRequestLog($logData));
      
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours