Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Monolog StderrColorFormatter using Collision\ConsoleColor
<?php
// config/logging.php
return [
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['stderr-color', 'daily'],
],
'stderr-color' => [
'driver' => 'monolog',
'handler' => StreamHandler::class,
'with' => ['stream' => 'php://stderr'],
'formatter' => StderrColorFormatter::class,
],
],
];
<?php
namespace Luchaos\MonologFormatter;
use Monolog\Formatter\LineFormatter;
use NunoMaduro\Collision\ConsoleColor;
use Psr\Log\LogLevel;
class StderrColorFormatter extends LineFormatter
{
public const SIMPLE_FORMAT = "[%datetime%] %message% %context% %extra%\n";
/**
* @see \NunoMaduro\Collision\ConsoleColor::STYLES
*/
private const STYLES = [
'[%datetime%]' => 'magenta',
'%context%' => 'light_green',
'%message%' => [
LogLevel::DEBUG => 'none',
LogLevel::INFO => 'green',
LogLevel::NOTICE => 'blue',
LogLevel::WARNING => 'yellow',
LogLevel::ERROR => ['red'],
LogLevel::CRITICAL => ['bg_red', 'white'],
LogLevel::ALERT => ['bg_red', 'white'],
LogLevel::EMERGENCY => ['bg_red', 'white'],
],
];
private ConsoleColor $color;
private bool $showDate;
public function __construct(
?string $format = null,
?string $dateFormat = 'Y-m-d H:i:s',
bool $allowInlineLineBreaks = false,
bool $ignoreEmptyContextAndExtra = true,
bool $showDate = true
) {
parent::__construct($format, $dateFormat, $allowInlineLineBreaks, $ignoreEmptyContextAndExtra);
$this->color = new ConsoleColor();
$this->showDate = $showDate;
}
public function format(array $record): string
{
$this->format = self::SIMPLE_FORMAT;
if (!$this->showDate) {
$this->format = str_replace('[%datetime%] ', '', $this->format);
}
foreach (self::STYLES as $key => $styled) {
$this->format = str_replace(
$key,
$this->color->apply($this->styles($key, mb_strtolower($record['level_name'])), $key),
$this->format
);
}
return parent::format($record);
}
private function styles(string $key, ?string $modifier = null): array
{
return (array) (self::STYLES[$key][$modifier] ?? self::STYLES[$key] ?? 'none');
}
}
<?php
namespace App\Actions;
use Illuminate\Support\Facades\Log;
class UsingColoredStderrLogging
{
public function __invoke()
{
Log::debug('Debug', ['some' => 'context']);
Log::debug('Info', ['some' => 'context']);
Log::debug('Notice', ['some' => 'context']);
Log::debug('Warning', ['some' => 'context']);
Log::debug('Error', ['some' => 'context']);
Log::debug('Critical', ['some' => 'context']);
Log::debug('Alert', ['some' => 'context']);
Log::debug('Emergency', ['some' => 'context']);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment