Weave 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

Loggable Command Bundle Laravel Package

bizkit/loggable-command-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install via Composer:
    composer require bizkit/loggable-command-bundle
    
  2. Enable the Bundle in config/bundles.php:
    return [
        // ...
        Bizkit\LoggableCommandBundle\BizkitLoggableCommandBundle::class => ['all' => true],
    ];
    
  3. Configure Monolog in config/packages/monolog.yaml:
    monolog:
        handlers:
            loggable_commands:
                type: stream
                path: "%kernel.logs_dir%/%kernel.environment%.log"
                level: debug
                channels: ["loggable_commands"]
    
  4. Annotate a Command (Symfony 5.4+ or PHP 8.0+):
    use Bizkit\LoggableCommandBundle\Attribute\Loggable;
    
    #[Loggable]
    class MyCommand extends Command
    {
        protected function execute(InputInterface $input, OutputInterface $output): int
        {
            $this->logger->info('Command executed');
            return Command::SUCCESS;
        }
    }
    
  5. Run the Command:
    php bin/console my:command
    
    Logs will now appear in a dedicated file (e.g., var/log/dev.loggable_commands).

First Use Case: Debugging a Complex Command

  • Use @Loggable on a command handling sensitive operations (e.g., payments, API calls).
  • Logs are auto-routed to var/log/{env}.loggable_commands, reducing noise in the main log.
  • Verify logs appear in real-time via tail -f var/log/dev.loggable_commands.

Implementation Patterns

1. Attribute vs. Annotation

  • PHP 8 Attributes (recommended for Symfony 5.4+):
    #[Loggable(level: 'debug', handler: 'custom_rotating')]
    class PaymentCommand extends Command { ... }
    
  • Doctrine Annotations (legacy support):
    /**
     * @Loggable(level="debug", handler="custom_rotating")
     */
    class LegacyCommand extends Command { ... }
    

2. Handler Customization

  • Default Handlers: Use stream or rotating_file via config:
    bizkit_loggable_command:
        default_handler: rotating_file
        handlers:
            rotating_file:
                type: rotating_file
                path: "%kernel.logs_dir%/commands/%kernel.environment%.log"
                max_files: 7
    
  • Custom Handlers: Extend LoggableHandlerFactory:
    class CustomHandlerFactory extends LoggableHandlerFactory
    {
        public function createHandler(array $config): HandlerInterface
        {
            return new FingerprintHandler(...);
        }
    }
    
    Register in config/packages/bizkit_loggable_command.yaml:
    bizkit_loggable_command:
        handler_factories:
            fingerprint: App\Handler\CustomHandlerFactory
    

3. Output Stream Control

  • Force stdout/stderr for specific levels:
    #[Loggable(level: 'error', stream: 'stderr')]
    class CriticalCommand extends Command { ... }
    
  • Override globally in config:
    bizkit_loggable_command:
        default_stream: stdout
    

4. Exclusive Channels

  • Auto-exclude loggable_commands from other handlers:
    monolog:
        handlers:
            main:
                type: stream
                path: "%kernel.logs_dir%/%kernel.environment%.log"
                channels: ["!loggable_commands"] # Exclude
    

5. Message Handlers (Messenger Integration)

  • Apply to Messenger handlers:
    #[Loggable]
    class ProcessPaymentHandler implements MessageHandlerInterface
    {
        public function __invoke(ProcessPaymentMessage $message)
        {
            $this->logger->info('Processing payment', ['amount' => $message->amount]);
        }
    }
    
  • Configure in config/packages/messenger.yaml:
    messenger:
        transports:
            async: { dsn: 'sync://' }
        routing:
            'App\Message\ProcessPaymentMessage': async
    

6. Dynamic Logging in Workflows

  • Pre/Post Hooks: Log command start/end:
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $this->logger->info('Command started', ['args' => $input->getArguments()]);
        try {
            // ...
        } finally {
            $this->logger->info('Command finished');
        }
        return Command::SUCCESS;
    }
    
  • Structured Logging: Use arrays for context:
    $this->logger->debug('User data', [
        'user_id' => $user->id,
        'action' => 'update_profile',
    ]);
    

Gotchas and Tips

Pitfalls

  1. Channel Mismatch:

    • Ensure monolog.yaml includes the loggable_commands channel:
      channels: ["loggable_commands"]
      
    • Symptom: Logs disappear silently. Fix: Check var/log/dev.log for errors.
  2. Handler Factory Not Found:

    • If using custom handlers, verify the factory class exists and is autowired.
    • Symptom: ClassNotFoundException. Fix: Clear cache (php bin/console cache:clear).
  3. PHP 7.2+ Attribute Parsing:

    • Attributes require PHP 7.4+ for full support. Use annotations for PHP 7.2–7.3.
    • Symptom: @Loggable ignored. Fix: Downgrade to annotations or upgrade PHP.
  4. Log Rotation Conflicts:

    • Rotating handlers may clash with Symfony’s default log rotation.
    • Fix: Explicitly set max_files and file_permission in config.
  5. Messenger Async Delays:

    • Logs for async handlers may appear out of order.
    • Workaround: Use sync transport for debugging or add timestamps:
      $this->logger->info('Async task', ['timestamp' => time()]);
      

Debugging Tips

  • Enable Debug Mode:
    bizkit_loggable_command:
        debug: true # Logs handler creation to main log
    
  • Check Handler Creation:
    • Inspect var/log/dev.log for lines like:
      [BizkitLoggableCommandBundle] Created handler 'rotating_file' for command 'app:my_command'
      
  • Temporary Console Output:
    • Override default_stream to stdout for quick checks:
      bizkit_loggable_command:
          default_stream: stdout
      

Extension Points

  1. Custom Attributes:

    • Extend LoggableAttribute to add metadata:
      #[Attribute]
      class PriorityLoggable extends LoggableAttribute
      {
          public function __construct(public int $priority = 1) {}
      }
      
    • Override LoggableCommandSubscriber to handle the new attribute.
  2. Handler Context:

    • Pass dynamic context to handlers:
      $handler = $this->get('loggable_command.handler_factory')->createHandler([
          'context' => ['user_id' => $user->id],
      ]);
      
  3. Log Level Overrides:

    • Dynamically adjust log levels at runtime:
      $this->logger->setLevel(LogLevel::DEBUG); // Override for a command
      
  4. Integration with ELK/Stackdriver:

    • Use the fingerprint handler to add structured metadata:
      bizkit_loggable_command:
          handlers:
              elk:
                  type: fingerprint
                  path: "%kernel.logs_dir%/elk.log"
                  fingerprint: ["@command_name", "@user_id"]
      

Performance Considerations

  • Avoid Over-Logging: High-volume commands (e.g., cron jobs) may bloat storage.
    • Solution: Use level: 'error' by default and add debug only where needed.
  • Handler Caching: The bundle caches handlers per command. Clear cache if configs change:
    php bin/console cache:clear bizkit_loggable_command
    
  • Async Logging: For high-throughput systems, consider async handlers (Symfony 5.3+):
    bizkit_loggable_command:
        handlers:
            async:
                type: async
                handler: stream
                buffer_size: 50
    
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.
htinlynn/genius-helper
maco-studios/hephaestus
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk
martialbe/flysystem-oss
chondal/3312client
jeroen-g/flickr
opscale-co/nova-genbi
itsjustvita/laravel-retention
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator