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

Logger Extra Bundle Laravel Package

deamon/logger-extra-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Package Add to composer.json:

    "require": {
        "deamon/logger-extra-bundle": "^7.0"
    }
    

    Run composer update.

  2. Configure Monolog Ensure your config/logging.php (Laravel) or config/packages/monolog.yml (Symfony) has a stream handler:

    'channels' => [
        'stack' => [
            'driver' => 'stack',
            'channels' => ['single', 'deprecations'],
        ],
        'single' => [
            'driver' => 'single',
            'path' => storage_path('logs/laravel.log'),
            'level' => env('LOG_LEVEL', 'debug'),
        ],
    ],
    
  3. Add Bundle Configuration Create config/deamon_logger_extra.php (Laravel) or config/packages/deamon_logger_extra.yml (Symfony):

    return [
        'application' => [
            'name' => 'my-laravel-app',
            'version' => '1.0.0',
        ],
        'handlers' => ['single'], // Match your Monolog handler name
        'config' => [
            'display' => [
                'user' => true,
                'client_ip' => true,
            ],
        ],
    ];
    
  4. First Use Case Log a request with context:

    \Log::debug('User action', [
        'custom_data' => 'test',
    ]);
    

    Expected log output:

    {
        "level": "debug",
        "message": "User action",
        "context": {
            "custom_data": "test",
            "user": {"id": 1, "name": "john"},
            "client_ip": "192.168.1.1",
            "application": {"name": "my-laravel-app", "version": "1.0.0"}
        }
    }
    

Implementation Patterns

Usage Patterns

  1. Context Injection

    • Automatic: The bundle injects predefined context (e.g., user, client_ip, route) into every log record for specified handlers.
    • Custom Context: Extend via a custom processor:
      use Deamon\LoggerExtraBundle\Processor\ExtraContextProcessor;
      use Monolog\Processor\ProcessorInterface;
      
      class CustomContextProcessor implements ProcessorInterface {
          public function __invoke(array $record): array {
              $record['extra']['custom_metric'] = 'value';
              return $record;
          }
      }
      
      // Register in AppServiceProvider
      \Monolog\Logger::pushProcessor(new CustomContextProcessor());
      
  2. Handler-Specific Configuration

    • Target specific Monolog handlers (e.g., single, stack) via the handlers config array.
    • Example: Log only to the single handler:
      'handlers' => ['single'],
      
  3. Conditional Display

    • Toggle context fields dynamically via display config:
      'config' => [
          'display' => [
              'user' => env('APP_ENV') !== 'production',
              'client_ip' => true,
          ],
      ],
      

Workflows

  1. Debugging Workflow

    • Enable all context fields in config/deamon_logger_extra.php:
      'config' => [
          'display' => [
              'env' => true,
              'locale' => true,
              'application_name' => true,
              'url' => true,
              'route' => true,
              'user_agent' => true,
              'accept_encoding' => true,
              'client_ip' => true,
              'user' => true,
              'global_channel' => true,
          ],
      ],
      
    • Log a request and inspect the output for missing/invalid fields.
  2. Performance Optimization

    • Disable unused context fields to reduce log size:
      'config' => [
          'display' => [
              'user' => false, // Disable if not needed
              'client_ip' => true,
          ],
      ],
      
  3. Integration with Laravel Logging

    • Use the bundle alongside Laravel’s built-in logging:
      // Log with custom context
      \Log::info('Order processed', [
          'order_id' => 123,
          'user_id' => auth()->id(),
      ]);
      
    • The bundle will merge its context with the provided array.

Integration Tips

  1. Avoid Symfony Dependencies

    • Exclude Symfony bundles from composer.json to prevent conflicts:
      "require": {
          "deamon/logger-extra-bundle": "^7.0",
          "symfony/security-core": null, // Explicitly remove
      },
      
    • Use only the Monolog processor classes directly if needed.
  2. Custom User Class

    • Override the default UserInterface for Laravel’s App\Models\User:
      'config' => [
          'user_class' => \App\Models\User::class,
          'user_methods' => [
              'user_name' => 'name', // Use 'name' instead of 'getUsername'
          ],
      ],
      
  3. Log Channel Routing

    • Route specific log levels to different handlers:
      'channels' => [
          'debug' => [
              'driver' => 'single',
              'path' => storage_path('logs/debug.log'),
              'level' => 'debug',
          ],
          'error' => [
              'driver' => 'single',
              'path' => storage_path('logs/error.log'),
              'level' => 'error',
          ],
      ],
      
    • Configure the bundle to target the debug handler:
      'handlers' => ['debug'],
      

Gotchas and Tips

Pitfalls

  1. Symfony Dependency Conflicts

    • Issue: The bundle pulls in Symfony dependencies (e.g., symfony/security-core), which may conflict with Laravel.
    • Fix: Explicitly remove Symfony bundles or use the processor classes directly:
      use Deamon\LoggerExtraBundle\Processor\ExtraContextProcessor;
      \Monolog\Logger::pushProcessor(new ExtraContextProcessor());
      
  2. Missing Context Fields

    • Issue: Context fields like user or client_ip may appear as null if not properly initialized.
    • Debugging:
      • Verify the user_class and user_methods are correctly configured.
      • Check if middleware (e.g., Authenticate for Laravel) populates the request/user data before logging.
  3. Handler Mismatch

    • Issue: Logs may not include extra context if the handler name in handlers config doesn’t match the Monolog handler.
    • Fix: Ensure the handler name matches exactly (e.g., single vs. stack).
  4. Performance Overhead

    • Issue: Injecting context into every log record can slow down logging in high-traffic apps.
    • Mitigation:
      • Disable unused context fields.
      • Use the bundle only for specific handlers (e.g., debug channel).
  5. Deprecation Warnings

    • Issue: Symfony deprecations may still appear if the bundle isn’t fully compatible with Laravel’s Monolog version.
    • Fix: Check the release notes for known issues and test thoroughly.

Debugging

  1. Log Context Inspection

    • Enable all context fields temporarily to verify data:
      'config' => [
          'display' => [
              'env' => true,
              'locale' => true,
              'application_name' => true,
              'url' => true,
              'route' => true,
              'user_agent' => true,
              'accept_encoding' => true,
              'client_ip' => true,
              'user' => true,
              'global_channel' => true,
          ],
      ],
      
    • Log a test request and inspect the output for missing or incorrect values.
  2. Processor Debugging

    • Temporarily add a debug processor to inspect the log record before context injection:
      \Monolog\Logger::pushProcessor(function ($record) {
          \Log::debug('Raw record before context:', $record);
          return $record;
      });
      
  3. Handler-Specific Logging

    • Test logging to different handlers to ensure context is injected correctly:
      \Log::debug('Test debug log', [], ['channel' => 'debug']);
      \Log::error('Test error log', [], ['channel' => 'error']);
      

Config Quirks

  1. Handler Name Sensitivity

    • The handlers config is case-sensitive and must match the Monolog handler name exactly (e.g., single vs. Single).
  2. User Class Requirements

    • The user_class must implement Laravel’s Illuminate\Contracts\Auth\Authenticatable or Symfony’s UserInterface.
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.
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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