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

Monolog Colored Line Formatter Laravel Package

bramus/monolog-colored-line-formatter

Adds a colored line formatter for Monolog, making console log output easier to scan with ANSI colors. Works as a drop-in formatter to highlight log levels, timestamps, and messages for CLI tools, workers, and development environments.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Monolog Integration: The package is a drop-in formatter for Monolog, Laravel’s default logging library, making it a zero-friction enhancement for existing logging pipelines. It leverages Monolog’s handler-processor-formatter architecture without modifying core functionality.
  • Terminal-Centric Design: Optimized for CLI/terminal output (ANSI color codes), aligning with Laravel’s Artisan, Tinker, and Sail ecosystems. Ideal for development environments where visual debugging accelerates workflows.
  • Non-Disruptive: Since it operates at the formatter level, it preserves all existing Monolog features (e.g., log levels, processors, handlers) while only enhancing output presentation.
  • Laravel-Specific Synergy: Works seamlessly with Laravel’s Log::stack(), config/logging.php, and environment-based logging configurations.

Integration Feasibility

  • Composer-First: Single-line installation (composer require bramus/monolog-colored-line-formatter) with no build steps or dependencies.
  • Configuration Flexibility:
    • Can be applied globally (all logs) or selectively (specific handlers/environments).
    • Supports customization via setColors() or subclassing for team-specific themes.
  • Laravel Ecosystem Compatibility:
    • Works with Artisan commands, Tinker, and Sail containers out of the box.
    • Integrates with Laravel’s log channels (e.g., single, daily, syslog) via handler configuration.
  • Backward Compatibility: Zero breaking changes—existing Monolog setups remain functional.

Technical Risk

  • ANSI Escape Sequence Pitfalls:
    • Production Logs: ANSI codes may corrupt parsing in log aggregation tools (e.g., ELK, Datadog, Papertrail) or file-based sinks. Risk mitigated by environment-specific toggling.
    • Windows Compatibility: ANSI colors do not render in default Windows CMD (works in PowerShell/WSL). Requires documentation or fallback mechanisms.
    • Log Analysis Tools: Scripts relying on grep, awk, or regex may fail if ANSI sequences are not stripped. Example:
      grep --color=never error.log  # Safely ignores ANSI
      
  • Performance: Negligible overhead (~5–10 bytes/log line), but not recommended for high-throughput logging (e.g., API request logs).
  • Testing Gaps:
    • CI/CD Logs: Ensure pipelines (GitHub Actions, GitLab CI) support ANSI (most do by default).
    • Legacy Systems: Older PHP versions (<7.4) or custom Monolog setups may require testing.

Key Questions

  1. Environment Scope:
    • Should the formatter be enabled only in local/development environments, or also in staging (where ANSI may still be useful)?
    • How will production logs handle ANSI codes (strip, ignore, or reject)?
  2. Handler Granularity:
    • Apply globally (all handlers) or selectively (e.g., only CLI-based handlers like stream to php://stdout)?
    • Example: Exclude file handlers (daily, single) from coloring in production.
  3. Fallback Strategy:
    • Implement a runtime check to disable colors in non-terminal environments (e.g., php_sapi_name() !== 'cli').
    • Use a custom processor to strip ANSI codes for production:
      $processor = new class implements \Monolog\Processor\ProcessorInterface {
          public function __invoke(array $record) {
              $record['formatted'] = preg_replace('/\x1B\[[0-9;]*m/', '', $record['formatted']);
              return $record;
          }
      };
      
  4. Toolchain Validation:
    • Test with log shippers (Fluentd, Logstash) and aggregators (ELK, Datadog) to confirm ANSI compatibility.
    • Verify IDE/log viewers (PHPStorm, VS Code) render colors correctly.
  5. Customization Needs:
    • Does the team need custom color schemes (e.g., team-branded colors) or additional metadata in logs?
    • Example: Extend the formatter to include timestamps in a specific format:
      $formatter = new \Bramus\Monolog\Formatter\ColoredLineFormatter(
          "[%datetime%] %channel%.%level_name%: %message%\n",
          "Y-m-d H:i:s",
          true
      );
      
  6. Security/Compliance:
    • Are there audit/logging policies that prohibit colored or "enhanced" log output?
    • Example: PCI/DSS or HIPAA environments may require plaintext logs.

Integration Approach

Stack Fit

  • Laravel Native: Designed for Laravel’s Monolog integration, with zero framework-level modifications.
  • CLI-Optimized: Ideal for:
    • Artisan Commands: Instant visual feedback for php artisan [command] output.
    • Tinker/REPL: Color-coded stack traces and variable dumps.
    • Sail Containers: Enhanced debugging in Dockerized environments.
  • Non-CLI Limitations:
    • HTTP Requests: Logs written to files/sinks (e.g., single, daily handlers) will not display colors in terminals.
    • External Services: Logs sent to syslog, Papertrail, or Datadog may include ANSI codes, risking parsing errors.

Migration Path

  1. Assessment Phase:
    • Audit current Monolog handlers in:
      • config/logging.php (default channels).
      • AppServiceProvider (custom log stack extensions).
      • Artisan commands (custom logging logic).
    • Identify CLI-specific handlers (e.g., stream to php://stdout) vs. file-based handlers (e.g., daily).
  2. Pilot Integration (Development-Only):
    • Add the package and configure the formatter only for local environments:
      // config/logging.php
      'channels' => [
          'colored' => [
              'driver' => 'single',
              'path' => storage_path('logs/laravel.log'),
              'level' => 'debug',
              'formatter' => \Bramus\Monolog\Formatter\ColoredLineFormatter::class,
          ],
      ],
      
    • Use environment-based switching:
      // app/Providers/AppServiceProvider.php
      public function boot()
      {
          if (app()->environment('local')) {
              $this->app['log']->stack(function ($stack) {
                  $stack->push(
                      (new \Monolog\Handler\StreamHandler(storage_path('logs/laravel.log')))
                          ->setFormatter(new \Bramus\Monolog\Formatter\ColoredLineFormatter())
                  );
              });
          }
      }
      
  3. Selective CLI Enhancement:
    • Extend to Artisan commands and Tinker by defaulting to the colored channel:
      // In an Artisan command
      public function handle()
      {
          Log::channel('colored')->info('Command started');
      }
      
    • For Sail, ensure Docker containers support ANSI (default in modern setups).
  4. Production Safeguards:
    • Strip ANSI codes for non-CLI handlers using a custom processor:
      $processor = new class implements \Monolog\Processor\ProcessorInterface {
          public function __invoke(array $record) {
              if (!app()->runningInConsole()) {
                  $record['formatted'] = preg_replace('/\x1B\[[0-9;]*m/', '', $record['formatted']);
              }
              return $record;
          }
      };
      $handler->pushProcessor($processor);
      
    • Validate CI/CD: Test GitHub Actions/GitLab CI logs to confirm ANSI rendering.

Compatibility

  • Monolog Versions: Compatible with Monolog 2.x (Laravel’s default) and 3.x. Pin version in composer.json if using edge cases.
  • PHP Versions: Supports PHP 7.4+ (Laravel’s minimum). No known issues with 8.0+.
  • Handler Types:
    • StreamHandler: Best for CLI (e.g., php://stdout).
    • File Handlers: ANSI codes will be written to files but won’t render in terminals.
    • Syslog/Socket: May transmit ANSI codes; test with downstream tools.
  • Laravel Versions: No version-specific issues reported (tested with Laravel 8+).

Sequencing

  1. Phase 1: Local Development Adoption
    • Goal: Improve CLI debugging for all developers.
    • Actions:
      • Install package and configure for local environment.
      • Update team documentation on colored log usage.
      • Gather feedback on usefulness and color scheme.
  2. **Phase 2: Artisan/Tinker
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.
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
spatie/mailcoach-vapor