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.
Install the Package Add the package to your Laravel project via Composer:
composer require bramus/monolog-colored-line-formatter
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
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).
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())
);
});
}
}
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');
}
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>',
]);
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())
);
});
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
ANSI in Production Logs
$processor = new class {
public function __invoke(array $record) {
$record['formatted'] = preg_replace('/\x1B\[[0-9;]*[mGK]/', '', $record['formatted']);
return $record;
}
};
$handler->pushProcessor($processor);
Windows Command Prompt
cmd.exe (works in PowerShell/WSL).if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
$formatter = new \Monolog\Formatter\LineFormatter();
} else {
$formatter = new \Bramus\Monolog\Formatter\ColoredLineFormatter();
}
Log File Bloat
Formatter Overrides
LineFormatter, ensure the colored formatter isn’t accidentally overridden.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.
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%']
);
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>'
]);
Dynamic Color Switching Change colors based on environment or log level:
$formatter = new \Bramus\Monolog\Formatter\ColoredLineFormatter();
if (app()->environment('production')) {
$formatter->setUseColor(false);
}
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,
],
How can I help you explore Laravel packages today?