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

Getting Started

Minimal Steps

  1. Install the Package Add the package to your Laravel project via Composer:

    composer require bramus/monolog-colored-line-formatter
    
  2. Configure Monolog Replace or extend your Monolog formatter in config/logging.php or a service provider (e.g., AppServiceProvider). For a development-only setup:

    // config/logging.php
    'channels' => [
        'colored' => [
            'driver' => 'single',
            'path' => storage_path('logs/laravel.log'),
            'level' => env('APP_DEBUG') ? 'debug' : 'info',
            'formatter' => \Bramus\Monolog\Formatter\ColoredLineFormatter::class,
        ],
    ],
    

    Then update your LOG_CHANNEL in .env:

    LOG_CHANNEL=colored
    
  3. Test Immediately Trigger a log entry in tinker or a CLI command:

    php artisan tinker
    Log::debug('This will appear in gray');
    Log::error('This will appear in red');
    

    Verify colors render in your terminal (e.g., errors in red, warnings in yellow).


Implementation Patterns

Core Workflows

  1. Environment-Specific Formatting Apply the formatter only in local/staging to avoid ANSI issues in production:

    // app/Providers/AppServiceProvider.php
    public function boot()
    {
        if (app()->environment(['local', 'staging'])) {
            $this->app['log']->stack(function ($stack) {
                $stack->push(
                    (new \Monolog\Handler\StreamHandler(storage_path('logs/laravel.log')))
                        ->setFormatter(new \Bramus\Monolog\Formatter\ColoredLineFormatter())
                );
            });
        }
    }
    
  2. CLI-Only Coloring Restrict the formatter to Artisan commands or Symfony Console outputs:

    // In a command class (e.g., app/Console/Commands/ExampleCommand.php)
    protected function configure()
    {
        $this->formatter = new \Bramus\Monolog\Formatter\ColoredLineFormatter();
        $this->logger = Log::channel('colored');
    }
    
  3. Custom Color Schemes Extend the formatter to match your team’s branding or accessibility needs:

    $formatter = new \Bramus\Monolog\Formatter\ColoredLineFormatter();
    $formatter->setColors([
        'DEBUG' => '<gray>',
        'INFO' => '<blue>',
        'WARNING' => '<yellow>',
        'ERROR' => '<red>',
        'CRITICAL' => '<bold;red>',
    ]);
    
  4. Integration with Laravel’s Log Stack Use Laravel’s Log::stack() to layer the formatter alongside other processors:

    Log::stack(function ($stack) {
        $stack->push(
            (new \Monolog\Handler\StreamHandler(storage_path('logs/laravel.log')))
                ->setFormatter(new \Bramus\Monolog\Formatter\ColoredLineFormatter())
                ->pushProcessor(new \Monolog\Processor\UidProcessor())
        );
    });
    

Pro Tips

  • Debugging Artisan Commands Override the handle() method in a command to inject colored logs:

    public function handle()
    {
        $this->info('Starting task...', ['formatter' => $this->formatter]);
        // Task logic
    }
    
  • IDE Integration Configure your IDE (e.g., PHPStorm) to ignore ANSI escape sequences in log files to avoid syntax highlighting issues.

  • CI/CD Pipelines Ensure your CI system (e.g., GitHub Actions) supports ANSI colors. Example for GitHub Actions:

    jobs:
      test:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v4
          - run: composer install
          - run: php artisan test  # Colors will render in GitHub's terminal
    

Gotchas and Tips

Pitfalls

  1. ANSI in Production Logs

    • Issue: ANSI codes may corrupt logs if parsed by tools (e.g., ELK, Datadog) or displayed in non-terminal environments.
    • Fix: Strip ANSI codes in production using a custom processor:
      $processor = new class {
          public function __invoke(array $record) {
              $record['formatted'] = preg_replace('/\x1B\[[0-9;]*[mGK]/', '', $record['formatted']);
              return $record;
          }
      };
      $handler->pushProcessor($processor);
      
  2. Windows Command Prompt

    • Issue: ANSI colors won’t display in cmd.exe (works in PowerShell/WSL).
    • Fix: Document requirements or use a fallback:
      if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
          $formatter = new \Monolog\Formatter\LineFormatter();
      } else {
          $formatter = new \Bramus\Monolog\Formatter\ColoredLineFormatter();
      }
      
  3. Log File Bloat

    • Issue: ANSI codes add ~5–10 bytes per log line.
    • Fix: Disable in non-debug environments or use a separate log file for colored output.
  4. Formatter Overrides

    • Issue: If you extend Monolog’s LineFormatter, ensure the colored formatter isn’t accidentally overridden.
    • Fix: Explicitly set the formatter in your handler configuration.

Debugging Tips

  • Verify Formatter is Applied Check if the formatter is active by logging a test message and inspecting the output:

    Log::debug('Test', ['context' => ['formatter' => get_class($handler->getFormatter())]]);
    

    Expected output: Bramus\Monolog\Formatter\ColoredLineFormatter.

  • Disable Colors Temporarily To debug log parsing issues, disable colors via:

    $formatter->setUseColor(false);
    
  • Check for Conflicting Processors Ensure no other Monolog processors (e.g., MemoryPeakUsageProcessor) are modifying the log format after the colored formatter.

Extension Points

  1. Custom Date/Time Formatting Override the default date format in the constructor:

    $formatter = new \Bramus\Monolog\Formatter\ColoredLineFormatter(
        '[%datetime%] %channel%.%level_name%: %message% %context% %extra%',
        ['datetime' => 'Y-m-d H:i:sP', 'channel' => '%channel%', 'level_name' => '%level_name%']
    );
    
  2. Add Stack Trace Highlighting Extend the formatter to bold stack traces for errors:

    $formatter = new \Bramus\Monolog\Formatter\ColoredLineFormatter();
    $formatter->setColors([
        'ERROR' => '<red>', 'stack_trace' => '<bold;red>'
    ]);
    
  3. Dynamic Color Switching Change colors based on environment or log level:

    $formatter = new \Bramus\Monolog\Formatter\ColoredLineFormatter();
    if (app()->environment('production')) {
        $formatter->setUseColor(false);
    }
    

Configuration Quirks

  • Laravel’s LOG_LEVEL Ensure LOG_LEVEL in .env doesn’t filter out critical logs (e.g., LOG_LEVEL=debug for local, info for production).

  • Handler Order Matters If using multiple handlers, the last formatter wins. Place the colored formatter on the handler you want to colorize.

  • Symfony Console Integration For Symfony Console commands, ensure the formatter is applied to the console channel:

    'console' => [
        'driver' => 'monolog',
        'handler' => 'stream',
        'formatter' => \Bramus\Monolog\Formatter\ColoredLineFormatter::class,
    ],
    
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