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

Saloon Logger Plug In Laravel Package

bit-mx/saloon-logger-plug-in

Laravel plug-in for Saloon v3 that logs HTTP requests, responses, and exceptions to the database with a shared ULID trace_id for end-to-end traceability. Includes automatic sanitization of sensitive headers/fields and simple trait-based setup.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require bit-mx/saloon-logger-plugin
    

    Register the plugin in your Saloon HTTP client:

    use BitMx\SaloonLoggerPlugin\SaloonLoggerPlugin;
    
    $client = Saloon::connect()
        ->withPlugin(new SaloonLoggerPlugin());
    
  2. First Use Case Log a request/response pair automatically:

    $response = $client->send(new YourRequest());
    // Logs are automatically captured via Saloon's lifecycle hooks
    
  3. Where to Look First

    • Plugin Class: SaloonLoggerPlugin.php Focus on handle() and onRequestSent()/onResponseReceived() methods.
    • Configuration: Check for config/saloon-logger.php (if provided) or default settings in the plugin class.
    • Logging Channel: Defaults to stack (Laravel’s default). Override via:
      $client->withPlugin(new SaloonLoggerPlugin(['channel' => 'single']));
      

Implementation Patterns

Core Workflow

  1. Automatic Logging The plugin hooks into Saloon’s RequestSent and ResponseReceived events, logging:

    • Request metadata (headers, body, URL).
    • Response metadata (status, body, headers).
    • Timing data (duration, start/end timestamps).
  2. Customizing Log Format Extend the plugin’s logger or override the formatLog() method:

    $plugin = new SaloonLoggerPlugin([
        'format' => function ($logData) {
            return "Custom: {$logData['request']['method']} {$logData['request']['url']}";
        }
    ]);
    
  3. Conditional Logging Filter logs by HTTP method, status code, or custom logic:

    $plugin = new SaloonLoggerPlugin([
        'shouldLog' => fn ($request, $response) =>
            $request->method() === 'POST' && $response->status() >= 400
    ]);
    
  4. Integration with Laravel Logging Use Laravel’s log channels (e.g., stack, single, daily):

    $client->withPlugin(new SaloonLoggerPlugin([
        'channel' => 'daily',
        'level' => 'debug'
    ]));
    
  5. Logging Exceptions Enable exception logging via:

    $plugin = new SaloonLoggerPlugin(['logExceptions' => true]);
    

Advanced Patterns

  • Log to External Services Override the log() method to push logs to tools like Sentry, Datadog, or custom APIs:

    $plugin = new SaloonLoggerPlugin([
        'logger' => new class {
            public function log($level, $message, array $context) {
                // Send to external service
            }
        }
    ]);
    
  • Request/Response Masking Sanitize sensitive data (e.g., passwords) before logging:

    $plugin = new SaloonLoggerPlugin([
        'masker' => fn ($data) => str_replace('password', '[REDACTED]', $data)
    ]);
    
  • Performance Monitoring Combine with Laravel’s stopwatch to track request durations:

    $plugin = new SaloonLoggerPlugin([
        'useStopwatch' => true
    ]);
    

Gotchas and Tips

Common Pitfalls

  1. Performance Overhead

    • Issue: Logging every request/response may slow down high-frequency APIs.
    • Fix: Use conditional logging (shouldLog) or disable for non-critical endpoints.
  2. Sensitive Data Leaks

    • Issue: Accidentally logging API keys, tokens, or PII.
    • Fix: Always use a masker or pre-process requests to redact sensitive fields.
  3. Log Channel Misconfiguration

    • Issue: Logs disappear if the channel isn’t properly configured (e.g., single channel not set up in config/logging.php).
    • Fix: Verify the channel exists and is accessible:
      $plugin = new SaloonLoggerPlugin(['channel' => 'stack']); // Fallback to default
      
  4. Event Hook Conflicts

    • Issue: Other Saloon plugins may override or conflict with the logger’s event hooks.
    • Fix: Register this plugin last in your client’s plugin chain.
  5. Large Payloads

    • Issue: Logging large JSON/XML responses may bloat storage or cause timeouts.
    • Fix: Truncate or hash large responses:
      $plugin = new SaloonLoggerPlugin([
          'maxResponseSize' => 1024, // Log only first 1KB
          'hashLargeResponses' => true
      ]);
      

Debugging Tips

  • Check Plugin Registration Ensure the plugin is attached to the client:

    $client->plugins(); // Verify SaloonLoggerPlugin is in the list
    
  • Inspect Log Levels Use Laravel’s log levels (debug, info, error) to control verbosity:

    $plugin = new SaloonLoggerPlugin(['level' => 'info']); // Skip debug logs
    
  • Test with a Minimal Request Isolate issues by testing with a simple GET request:

    $response = $client->send(new (\Saloon\Http\Concerns\Body)());
    
  • Enable Debug Mode Temporarily enable Saloon’s debug mode to see raw request/response data:

    $client = Saloon::connect()->withDebug();
    

Extension Points

  1. Custom Loggers Implement BitMx\SaloonLoggerPlugin\Contracts\Logger to create a custom logger:

    class MyLogger implements Logger {
        public function log($level, $message, array $context) {
            // Custom logic (e.g., write to a file, database, or queue)
        }
    }
    
  2. Event Subscriptions Extend the plugin to listen to additional Saloon events (e.g., RequestFailed):

    $plugin->extend(function ($plugin) {
        $plugin->onRequestFailed(fn ($request, $exception) => Log::error(
            "Request failed: {$exception->getMessage()}",
            ['request' => $request->resolve()]
        ));
    });
    
  3. Dynamic Configuration Load settings from environment variables or config files:

    $plugin = new SaloonLoggerPlugin([
        'channel' => config('saloon-logger.channel', 'stack'),
        'level' => env('SALOON_LOG_LEVEL', 'debug')
    ]);
    
  4. Async Logging Offload logging to a queue for high-throughput systems:

    $plugin = new SaloonLoggerPlugin([
        'logger' => new AsyncLogger()
    ]);
    
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.
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony
spatie/flare-daemon-runtime