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 Log Dumper Laravel Package

spatie/laravel-log-dumper

Adds an ld() helper to dump any values to your Laravel application log using Symfony VarDumper formatting. Log multiple arguments, choose or chain log levels (info/debug/error/etc.), and enable/disable logging when needed.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/laravel-log-dumper
    

    No additional configuration is required—just use the ld() helper function globally.

  2. First Use Case: Replace dd() or dump() calls with ld() to log variables to Laravel’s default log channel (e.g., single, daily, or stack).

    ld($user, $request->all(), $this->someComplexObject);
    

    Outputs structured logs with Symfony’s VarDumper formatting.

  3. Where to Look First:


Implementation Patterns

Core Workflows

  1. Debugging in Production: Replace dd() in production to avoid halting execution:

    // Instead of:
    dd($user->roles); // Crashes app
    
    // Use:
    ld($user->roles); // Logs to file/database without stopping
    
  2. Structured Logging: Log complex objects (e.g., Eloquent models, API responses) with automatic type casting:

    ld([
        'user' => $user->toArray(),
        'request' => $request->except('password'),
        'exception' => $e->getTraceAsString(),
    ]);
    
  3. Integration with Monolog: Leverage Laravel’s log channels (e.g., stack, slack, papertrail) by default:

    // Log to a custom channel (e.g., 'error-logger'):
    ld($error, channel: 'error-logger');
    
  4. Conditional Logging: Use in if blocks or middleware to log only under specific conditions:

    if ($request->has('debug')) {
        ld('Debug mode enabled', $request->all());
    }
    
  5. Testing: Mock ld() in tests to verify log output:

    $this->expectsLogs(function () {
        ld('Test log entry');
    });
    

Advanced Patterns

  • Log Context: Attach metadata (e.g., user ID, request ID) to logs:

    ld('Payment processed', context: ['user_id' => auth()->id(), 'tx_id' => $txId]);
    
  • Performance Logging: Log execution time alongside data:

    $start = microtime(true);
    $result = $this->processData();
    ld('Processing time', microtime(true) - $start, $result);
    
  • Exception Handling: Log exceptions with stack traces in App\Exceptions\Handler:

    public function report(Throwable $e) {
        ld($e, context: ['url' => request()->url()]);
    }
    

Gotchas and Tips

Pitfalls

  1. Performance Overhead:

    • Avoid logging large datasets (e.g., ld($users->all())) in loops or high-traffic endpoints.
    • Fix: Use ld()->only(['id', 'name']) or chunk data.
  2. Log Channel Mismatch:

    • ld() defaults to Laravel’s default log channel. If using a custom channel (e.g., slack), ensure it’s configured in config/logging.php.
    • Fix: Explicitly specify the channel:
      ld($data, channel: 'slack');
      
  3. Sensitive Data Leaks:

    • Logging passwords, tokens, or PII can expose security risks.
    • Fix: Redact sensitive fields:
      ld($request->except('password', 'api_token'));
      
  4. VarDumper Limitations:

    • Circular references or closures may cause infinite loops or truncated output.
    • Fix: Use ld()->maxDepth(2) to limit recursion depth.
  5. Log Rotation:

    • Large log files can bloat storage. Configure log_max_files in config/logging.php to rotate logs.

Debugging Tips

  • Verify Log Output: Check logs in storage/logs/laravel.log (or your configured path). Use tail -f storage/logs/laravel.log in CLI.

  • Log Levels: Override the default log level (e.g., debug) via config:

    'log_dumper' => [
        'level' => 'info', // or 'debug', 'error'
    ],
    
  • Custom Formatters: Extend the dumper’s behavior by publishing the config:

    php artisan vendor:publish --provider="Spatie\LogDumper\LogDumperServiceProvider"
    

    Then modify config/log-dumper.php to add custom formatters or filters.

Extension Points

  1. Custom Log Channels: Create a dedicated channel for ld() logs:

    // config/logging.php
    'channels' => [
        'log_dumper' => [
            'driver' => 'single',
            'path' => storage_path('logs/debug.log'),
            'level' => 'debug',
        ],
    ],
    

    Then use:

    ld($data, channel: 'log_dumper');
    
  2. Pre-Log Hooks: Add middleware to transform data before logging:

    // app/Providers/AppServiceProvider.php
    public function boot() {
        LogDumper::macro('sanitize', function ($data) {
            return collect($data)->mapWithKeys(function ($value, $key) {
                return str_contains($key, 'password') ? '[REDACTED]' : $value;
            });
        });
    }
    

    Usage:

    ld($request->all())->sanitize();
    
  3. Log to External Services: Use Monolog handlers to forward logs to services like Datadog or Sentry:

    // config/logging.php
    'channels' => [
        'log_dumper' => [
            'driver' => 'monolog',
            'handler' => \Monolog\Handler\DatadogHandler::class,
        ],
    ],
    
  4. Conditional Logging in Production: Disable ld() in production via config:

    // config/log-dumper.php
    'enabled' => env('APP_ENV') !== 'production',
    
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