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

Symfonylogbundle Laravel Package

bexlardi/symfonylogbundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer:

    composer require bexlardi/symfonylogbundle
    

    Register the bundle in config/bundles.php (Symfony):

    return [
        // ...
        Bexlardi\SymfonyLogBundle\BexlardiSymfonyLogBundle::class => ['all' => true],
    ];
    
  2. Configuration Publish the default config:

    php artisan vendor:publish --provider="Bexlardi\SymfonyLogBundle\BexlardiSymfonyLogBundle" --tag="config"
    

    Edit config/symfony_log.php to define log channels, handlers, and formatters.

  3. First Use Case Inject the logger into a service/controller:

    use Psr\Log\LoggerInterface;
    
    class MyController extends Controller
    {
        public function __construct(private LoggerInterface $logger)
        {
            $this->logger->info('Application started', ['context' => 'startup']);
        }
    }
    

Implementation Patterns

Logging Workflows

  1. Structured Logging Use associative arrays for context:

    $this->logger->debug('User action', [
        'user_id' => $user->id,
        'action' => 'profile_update',
        'ip' => $request->ip(),
    ]);
    
  2. Channel-Specific Logging Route logs to different handlers (e.g., app, security, audit):

    $this->logger->channel('audit')->info('Admin action', ['user' => $user->email]);
    
  3. Exception Handling Log exceptions with stack traces:

    try {
        // Risky operation
    } catch (\Exception $e) {
        $this->logger->error('Operation failed', [
            'exception' => $e->getMessage(),
            'trace' => $e->getTraceAsString(),
        ]);
    }
    
  4. Monolog Integration Extend Monolog handlers (e.g., StreamHandler, FingersCrossedHandler):

    $this->logger->pushHandler(new \Monolog\Handler\StreamHandler(
        storage_path('logs/custom.log'),
        \Monolog\Logger::DEBUG
    ));
    
  5. Middleware for Request Logging Log HTTP requests/responses in middleware:

    public function handle($request, Closure $next)
    {
        $this->logger->info('Incoming request', [
            'method' => $request->method(),
            'path' => $request->path(),
            'ip' => $request->ip(),
        ]);
    
        $response = $next($request);
        $this->logger->info('Request completed', [
            'status' => $response->getStatusCode(),
        ]);
    
        return $response;
    }
    
  6. Event-Based Logging Log critical events via Symfony’s event dispatcher:

    $dispatcher->addListener('user.registered', function ($event) {
        $this->logger->info('User registered', [
            'email' => $event->getUser()->getEmail(),
        ]);
    });
    

Gotchas and Tips

Common Pitfalls

  1. Channel Mismatch

    • Ensure log channels defined in config/symfony_log.php match those used in code.
    • Debug with:
      $this->logger->getHandlers(); // Check active handlers
      
  2. Performance Overhead

    • Avoid logging in tight loops or high-frequency operations (e.g., API rate limiting).
    • Use debug() or verbose() for development; info()/warning() for production.
  3. Log Rotation

    • Configure max_files and file_permission in handlers to prevent disk issues:
      'handlers' => [
          'main' => [
              'type' => 'stream',
              'path' => '%kernel.logs_dir%/%kernel.environment%.log',
              'level' => 'debug',
              'max_files' => 30, // Rotate after 30 files
          ],
      ],
      
  4. Sensitive Data

    • Never log passwords, tokens, or PII (Personally Identifiable Information).
    • Use masking in context:
      $this->logger->info('Login attempt', [
          'email' => $user->email,
          'password' => '********', // Manually mask
      ]);
      
  5. Symfony vs. Laravel Quirks

    • Dependency Injection: Use autowire: true in services.yaml for Laravel compatibility:
      services:
          App\Services\MyService:
              arguments:
                  $logger: '@logger'
      
    • Container Awareness: The bundle assumes Symfony’s ContainerInterface. For Laravel, bind the logger manually:
      $this->app->bind('logger', function () {
          return new \Monolog\Logger('app', $this->app['monolog.handler']);
      });
      

Debugging Tips

  1. Check Log Levels

    • Default levels: debug > info > notice > warning > error > critical > alert > emergency.
    • Temporarily lower levels in config for debugging:
      'handlers' => [
          'main' => ['level' => 'debug'], // Log everything
      ],
      
  2. Handler-Specific Issues

    • StreamHandler: Verify path is writable (chmod -R 775 storage/logs).
    • FingersCrossedHandler: Ensure action_level is set to bubble up critical logs.
  3. Log Formatting

    • Customize formatters in config:
      'formatters' => [
          'custom' => [
              'format' => '%datetime% | %level_name% | %message% %context% %extra%',
          ],
      ],
      
  4. Laravel-Specific Fixes

    • If using Laravel’s Log facade, alias the bundle’s logger:
      Log::shouldUseDailyFiles(); // Use Laravel’s default
      Log::info('Test', ['logger' => 'SymfonyLogBundle']);
      

Extension Points

  1. Custom Handlers Extend Bexlardi\SymfonyLogBundle\Handler\AbstractHandler for bespoke logging (e.g., Slack, Datadog).

  2. Processor Integration Add Monolog processors for data enrichment:

    $processor = new \Monolog\Processor\UidProcessor();
    $this->logger->pushProcessor($processor);
    
  3. Dynamic Channels Create channels programmatically:

    $channel = $this->logger->channel('dynamic_channel');
    $channel->info('Dynamic log');
    
  4. Log Enrichment Use middleware to add metadata (e.g., user ID, request ID):

    $this->logger->pushProcessor(function (array $record) {
        $record['extra']['request_id'] = $this->getRequestId();
        return $record;
    });
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui