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

Command Logger Bundle Laravel Package

ayaou/command-logger-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require ayaou/command-logger-bundle
    
  2. Enable the bundle in config/bundles.php:
    Ayaou\CommandLoggerBundle\AyaouCommandLoggerBundle::class => ['all' => true],
    
  3. Configure logging in config/packages/command_logger.yaml:
    command_logger:
      enabled: true
    
  4. Run migrations to create the command_log table:
    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    

First Use Case

Annotate a command to log its execution:

use Ayaou\CommandLoggerBundle\Attribute\CommandLogger;
use Symfony\Component\Console\Attribute\AsCommand;

#[AsCommand(name: 'app:test-command')]
#[CommandLogger]
class TestCommand extends Command
{
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $output->writeln('Test command executed!');
        return Command::SUCCESS;
    }
}

Run the command:

php bin/console app:test-command

Verify logs:

php bin/console command-logger:show

Implementation Patterns

1. Selective Logging via Configuration

Use the commands array in command_logger.yaml to log specific commands without annotations:

command_logger:
  commands:
    - app:cron-job:*
    - make:migration
    - make:model
  • Wildcards (*) support partial command names (e.g., app:cron-job:* logs all app:cron-job-* commands).
  • Third-party commands: Log commands from other bundles (e.g., doctrine:migrations:migrate).

2. Logging All Commands

Disable selective logging and enable global logging:

command_logger:
  enabled: true
  commands: []  # Empty array logs all commands

3. Integrating with Existing Commands

For commands without annotations, ensure they’re listed in the commands config. For new commands, prefer the #[CommandLogger] attribute:

#[AsCommand(name: 'app:deploy')]
#[CommandLogger]
class DeployCommand extends Command { ... }

4. Querying Logs Programmatically

Use the CommandLoggerRepository service to fetch logs in custom logic:

use Ayaou\CommandLoggerBundle\Repository\CommandLoggerRepository;

class MyService {
    public function __construct(
        private CommandLoggerRepository $loggerRepo
    ) {}

    public function getFailedDeployments(): array {
        return $this->loggerRepo->findBy([
            'commandName' => 'app:deploy',
            'exitCode' => Command::FAILURE
        ]);
    }
}

5. Automated Log Purging

  • Scheduled purging: Add a cron job to run command-logger:purge periodically (e.g., weekly):
    0 0 * * 0 php bin/console command-logger:purge --threshold=30
    
  • Manual purging: Run ad-hoc cleanup:
    php bin/console command-logger:purge --threshold=90
    

6. Error Handling and Debugging

  • Filter errors in logs:
    php bin/console command-logger:show --error
    
  • Inspect specific failures by ID:
    php bin/console command-logger:show --id=123
    

Gotchas and Tips

1. Attribute vs. Configuration Conflicts

  • Issue: Commands annotated with #[CommandLogger] override config-based logging.
  • Fix: Use either annotations or config lists, not both for the same command.
  • Workaround: Exclude annotated commands from the commands config to avoid duplicates.

2. Wildcard Matching Quirks

  • Behavior: Wildcards (*) match suffixes only (e.g., app:cron-job:* matches app:cron-job:daily but not app:cron-job-backup).
  • Tip: Use multiple entries for broader matching:
    commands:
      - app:cron-job:*
      - app:cron-*
    

3. Doctrine ORM Version Compatibility

  • Symfony 6/7: Uses Doctrine ORM 2 by default.
  • Symfony 8: Requires Doctrine ORM 3 (supported since v1.4.0).
  • Fix: Update composer.json if using Symfony 8:
    composer require doctrine/orm:^3.0
    

4. Performance Impact

  • High-volume commands: Logging adds ~5–10ms overhead per execution.
  • Mitigation:
    • Disable logging for non-critical commands (e.g., make:test).
    • Increase purge_threshold to reduce database bloat.

5. Debugging Missing Logs

  • Check enabled status: Verify enabled: true in config.
  • Validate command names: Ensure names match exactly (case-sensitive, e.g., app:deploy vs. APP:DEPLOY).
  • Symfony 7.3+ Compatibility: If using Symfony 7.3+, ensure the bundle is updated to v1.6.0+ (see #22).

6. Extending Log Storage

  • Custom fields: Extend the CommandLog entity to add metadata (e.g., userId, environment):
    // src/Entity/CommandLog.php
    #[ORM\Entity]
    class CommandLog extends BaseCommandLog {
        #[ORM\Column(type: 'string', nullable: true)]
        private ?string $environment = null;
    }
    
  • Hook into logging: Override the CommandLogger service to inject custom logic:
    # config/services.yaml
    Ayaou\CommandLoggerBundle\Service\CommandLogger:
      arguments:
        $environment: '%kernel.environment%'
    

7. CLI Output vs. Log Accuracy

  • Note: Logs capture raw arguments, not processed values. For complex arguments (e.g., objects), serialize manually:
    $output->writeln(json_encode($input->getArgument('data')));
    

8. Purging Edge Cases

  • Manual override: The --threshold flag in command-logger:purge ignores the config value.
  • Safety: Test purging in a staging environment first to avoid data loss.

9. Symfony 8+ Command Style

  • New style: Symfony 8+ uses #[AsCommand] instead of setName(). The bundle supports this natively (v1.6.0+).
  • Legacy support: Older styles (setName()) still work but may require updates for full compatibility.
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.
nasirkhan/laravel-sharekit
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