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

Command Logger Bundle Laravel Package

ayaou/command-logger-bundle

Symfony bundle that logs executed console commands with arguments, execution time, exit codes, and errors. Configure via attributes or wildcard patterns, view and filter logs with the command-logger:show command.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Symfony/Laravel Compatibility: The bundle remains Symfony-first, but its core functionality—logging console command executions—can be adapted for Laravel via a custom wrapper, middleware, or Artisan event hooks. Laravel’s Artisan CLI shares similar command execution patterns, so the adaptation path is unchanged.
  • Database Dependency: Relies on Doctrine ORM for storing logs in a command_log table. Laravel’s Eloquent or Query Builder can replace this. v1.11.0 adds opt-in storage of captured command output, which requires an additional output column (likely TEXT/LONGTEXT or JSON) and corresponding Eloquent cast.
  • Event-Driven Hooks: Leverages Symfony’s event system. Laravel’s Artisan::starting/Artisan::finished events or middleware can replicate this behavior.
  • Attribute-Based Logging: Uses Symfony’s #[CommandLogger] attribute. Laravel can use traits, custom attributes (PHP 8.0+), or annotations for equivalent functionality.
  • Output Capture (New in v1.11.0): The bundle now optionally stores what a watched command printed and displays it via command-logger:show. This introduces a new data-capture concern: output may be large, multi-line, or contain sensitive information. Laravel integration must decide whether to buffer Artisan output directly, use Symfony\Component\Console\Output\BufferedOutput, or wrap command execution to capture stdout/stderr.

Integration Feasibility

  • Low Code Overhead: Minimal changes required to adapt for Laravel:
    • Replace Doctrine with Eloquent for log storage.
    • Replace Symfony events with Laravel’s Artisan hooks or middleware.
    • Port the CommandLogger attribute to Laravel’s attribute system or annotations.
    • Add an opt-in config flag (e.g., command_logger.capture_output) and a migration for the output column.
    • Extend the command-logger:show equivalent to render captured output (with truncation/formatting).
  • Configuration Flexibility: Supports attribute-based and YAML-based command whitelisting. Laravel’s config/ system can mirror this, including the new output-capture opt-in flag. Consider per-command opt-in as well as global enablement.
  • Existing CLI Tools: The command-logger:show and command-logger:purge commands can be replicated as Laravel Artisan commands. show should gain an option to display captured output (e.g., --output or automatic when present).

Technical Risk

  • Symfony-Specific Abstractions: Risk of tight coupling to Symfony’s Console component. Mitigation: abstract dependencies behind interfaces.
  • Database Schema Mismatch: Laravel’s Eloquent may require adjustments to the command_log table schema (timestamps, JSON fields). v1.11.0 adds an output column, requiring a migration and consideration of storage type (TEXT vs. file/object storage) for large outputs.
  • Performance Impact: Logging every command adds overhead. Output capture can significantly increase overhead and storage volume, especially for verbose commands. Mitigation: keep output capture opt-in, truncate aggressively, disable for high-volume or production commands, or use async logging.
  • Sensitive Data Exposure: Captured output may contain secrets, tokens, PII, or internal paths. Mitigation: redaction rules, output truncation, per-command allowlists, and retention limits.
  • Wildcard Command Matching: Symfony’s wildcard support (make:*) may not translate directly to Laravel’s command resolution. Custom logic may be needed.
  • Output Capture Reliability: Buffering output can interfere with interactive commands or commands that stream output. Ensure capture failures do not break command execution.

Key Questions

  1. Prioritization:
    • Is observability of command executions a critical need (debugging, auditing) or nice-to-have?
    • Does the new output-capture feature materially improve debugging enough to justify storage and privacy risks?
  2. Scope:
    • Should all commands be logged, or only specific ones?
    • Should output capture be enabled globally, per command, or only in non-production environments?
    • Are there commands whose output must never be stored (e.g., commands printing credentials)?
  3. Storage:
    • Should logs persist in a database, or could they be written to files or an external service?
    • For captured output: store inline in the database, truncate, or offload to object storage?
  4. Retention:
    • What is the acceptable log retention period (default: 100 days)? Does output capture require a shorter retention?
  5. Security/Compliance:
    • What redaction or masking is required before storing output?
    • Are there compliance constraints (GDPR, SOC2) on storing command output?
  6. Alternatives:
    • Could existing tools (Laravel’s built-in logging, spatie/laravel-command, CI logs) meet the need with less effort?
  7. Testing:
    • How will logs and captured output be validated in CI/CD?
    • Should output be exported for post-mortems or compliance?

Integration Approach

Stack Fit

  • Laravel Compatibility:
    • Artisan CLI: Directly compatible with Laravel’s command structure.
    • Database: Replace Doctrine with Eloquent (supports JSON fields for arguments; add a TEXT/LONGTEXT column for captured output).
    • Events: Use Laravel’s Artisan::starting/Artisan::finished events or middleware to intercept commands.
    • Attributes: Implement custom attributes (PHP 8.0+) or annotations for command logging.
    • Output Capture: Use Laravel’s process output buffering or Symfony’s BufferedOutput within a wrapper. Expose an opt-in config flag.
  • Symfony vs. Laravel Differences:
    Feature Symfony Implementation Laravel Adaptation
    Command Registration #[AsCommand] attribute Artisan::command() or #[ConsoleCommand]
    Event System console.command events Artisan::starting/finished events
    Configuration YAML (config/packages/) PHP (config/command_logger.php)
    Database ORM Doctrine Eloquent
    Output Capture Opt-in flag in v1.11.0 Opt-in config flag + buffered output

Migration Path

  1. Phase 1: Proof of Concept (1–2 weeks)
    • Create a minimal Laravel wrapper for the bundle’s core logic:
      • Intercept Artisan commands using middleware or events.
      • Store logs in a custom Eloquent model (CommandLog).
      • Test with 2–3 critical commands (e.g., migrate, queue:work).
    • Example middleware:
      public function handle($request, Closure $next) {
          if ($request->isConsole()) {
              $start = microtime(true);
              try {
                  $response = $next($request);
                  $this->logCommand($request->command, $response->exitCode, null, $start);
              } catch (\Exception $e) {
                  $this->logCommand($request->command, 1, $e->getMessage(), $start);
                  throw $e;
              }
          }
          return $next($request);
      }
      
    • v1.11.0 PoC addition: Prototype output capture behind a config flag. Use a buffered output wrapper and store a truncated sample in a new output column. Validate that interactive/streaming commands are not broken.
  2. Phase 2: Full Integration (2–3 weeks)
    • Replace Doctrine with Eloquent:
      // app/Models/CommandLog.php
      class CommandLog extends Model {
          protected $casts = [
              'arguments' => 'json',
              'output' => 'string',
          ];
      }
      
    • Add migration for output column (nullable, TEXT/LONGTEXT). Consider a separate table or object storage if output volume is high.
    • Port configuration to Laravel’s config/ system, including capture_output and per-command allowlists.
    • Implement attribute-based logging (e.g., #[LogCommand]) with optional output capture.
    • Add CLI commands (command-logger:show, command-logger:purge) as Artisan commands. Extend show to render captured output with truncation and optional --output flag.
  3. Phase 3: Optimization (1 week)
    • Add async logging (queue jobs) for performance-sensitive commands, including async output storage if needed.
    • Implement wildcard command matching for Laravel’s command resolution.
    • Add filters to the show command (e.g., --error, --success, --with-output).
    • Implement output redaction/truncation rules.

Compatibility

  • Laravel Versions: Supports PHP 8.1+ (Laravel 9+). Tested up to Symfony 8 (Laravel’s future versions may require adjustments).
  • Third-Party Commands: Wildcard support (make:*) may need custom logic for Laravel’s command loader.
  • Existing Logging: Can coexist with Monolog but may duplicate logs. Consider deduplication or routing logs to a separate channel.
  • Output Capture Compatibility: Commands using interactive prompts or real-time streaming may not work well with buffered capture. Ensure opt-in is per command and can be skipped for such commands.

Sequencing

  1. Prerequisites:
    • Ensure Laravel’s database is compatible with the command_log schema.
    • Resolve any conflicts with existing Artisan events/middleware.
    • Decide output-capture policy (global, per command, environment-based).
  2. Core Implementation:
    • Start with middleware-based logging (lowest risk).
    • Add output capture behind an opt-in flag only after core logging is stable.
  3. Schema Migration:
    • Add output column migration before enabling capture in any environment.
  4. CLI Tools:
    • Implement command-logger:show and command-logger:purge last (depends on storage layer). Include output rendering and redaction.
  5. Testing:
    • Validate logs and captured output for critical commands in staging.
    • Performance-test with high-command-volume environments (e.g., CI) and verbose commands.
    • Test redaction and truncation behavior.

Operational Impact

Maintenance

  • Dependencies:
    • Laravel-specific: Eloquent, Artisan events, custom attributes.
    • Symfony-specific: Doctrine, Symfony events (minimal if abstracted).
    • Risk: Future Laravel/Symfony updates may require bundle adjustments (e.g., Symfony 8 support in v1.6.0, output-capture API changes in v1.11.0).
  • Configuration:
    • Centralized in config/command_logger.php (e.g., enabled, purge threshold, command whitelist, capture_output, output truncation limit).
    • Tooling: Use Laravel’s config:cache to optimize performance.
  • Updates:
    • Monitor for upstream Symfony changes (e.g., event system deprecations).
    • Plan for annual bundle updates (e.g., Symfony 9/Laravel 11 compatibility).
    • Review output-capture behavior on each release because it touches command execution internals.

Support

  • Debugging:
    • Logs provide an audit trail for command failures (e.g., exitCode: 1, errorMessage).
    • v1.11.0 improvement: Captured output makes silent failures much easier to diagnose (e.g., a migration that failed with a stack trace or validation message).
    • Example Use Case: Debugging a silent migrate failure in CI by inspecting both the exit code and the captured error output.
  • Troubleshooting:
    • command-logger:show --error helps identify flaky commands.
    • command-logger:show --with-output helps inspect command stdout/stderr.
    • Limitations: No support for nested command execution (e.g., commands called from other commands).
    • New limitation: Output capture may miss or truncate very large outputs; interactive commands may not be fully captured.
  • Documentation:
    • Update Laravel-specific docs for:
      • Attribute usage (#[LogCommand]).
      • CLI command syntax (e.g., php artisan command-logger:show --limit=20 --with-output).
      • Output-capture opt-in, truncation, redaction, and retention.
    • Example: Add a README.md section for Laravel integration, including a security note about sensitive output.

Scaling

  • Performance:
    • Synchronous Logging: Adds ~1–5ms per command (negligible for most use cases).
    • Output Capture: Can add significant overhead for verbose commands. Mitigation: opt-in only, truncate at a configurable limit, and disable for high-frequency commands.
    • Async Logging: Use Laravel queues to offload logging for long-running commands (e.g., queue:work). Output capture may need to be synchronous or buffered before dispatch.
    • Database Load: Index startTime and commandName for fast queries in command-logger:show. Output column increases row size; consider separate storage if large.
  • Log Volume:
    • Retention: Default 100-day purge threshold may need adjustment (e.g., 30 days for high-volume systems). Output retention may need to be shorter.
    • Archiving: Consider exporting logs and output to cold storage or external observability platforms.
    • Storage Growth: Output capture can multiply storage requirements. Monitor table size and purge jobs.
  • Failure Modes:
    • Output capture failure should not fail the command. Use try/catch and fall back to logging without output.
    • Buffer exhaustion or memory limits on very verbose commands. Enforce a maximum output size.
    • Sensitive data leakage into logs. Implement redaction and access controls.
  • Ramp-up:
    • Start with command logging only; enable output capture for a small set of non-sensitive commands.
    • Train teams on output-capture risks and redaction expectations.
    • Gradually expand allowlist based on demonstrated debugging value.
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