Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
"symfony/serializer": "^7.2",
"phpstan/phpdoc-parser": "^2.0",
"phpdocumentor/reflection-docblock": "^5.6",
"wondernetwork/php-collection-library": "^10.0"
"wondernetwork/php-collection-library": "^10.0",
"monolog/monolog": "^3.10"
},
"license": "MIT",
"autoload": {
Expand All @@ -34,6 +35,9 @@
"tests/Resources/App/src/",
"tests/Resources/ErrorMiddleware/src/",
"tests/Resources/Messenger/src/"
],
"Acme\\ConsoleLogger\\": [
"tests/Resources/ConsoleLogger/src/"
]
}
},
Expand Down
105 changes: 104 additions & 1 deletion composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

37 changes: 37 additions & 0 deletions src/Cli/Logging/ConsoleHandlerEventSubscriber.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

declare(strict_types=1);

namespace WonderNetwork\SlimKernel\Cli\Logging;

use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

final readonly class ConsoleHandlerEventSubscriber implements EventSubscriberInterface {
public static function getSubscribedEvents(): array {
return [
ConsoleEvents::COMMAND => 'onCommand',
ConsoleEvents::TERMINATE => 'onTerminate',
];
}

public function __construct(private ConsoleIoStack $consoleIoStack) {
}

public function onCommand(ConsoleCommandEvent $event): void {
$input = $event->getInput();
$output = $event->getOutput();

if ($output instanceof ConsoleOutputInterface) {
$output = $output->getErrorOutput();
}

$this->consoleIoStack->push(new ConsoleIo($input, $output));
}

public function onTerminate(): void {
$this->consoleIoStack->pop();
}
}
16 changes: 16 additions & 0 deletions src/Cli/Logging/ConsoleIo.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

declare(strict_types=1);

namespace WonderNetwork\SlimKernel\Cli\Logging;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

final readonly class ConsoleIo {
public function __construct(
public InputInterface $input,
public OutputInterface $output,
) {
}
}
36 changes: 36 additions & 0 deletions src/Cli/Logging/ConsoleIoStack.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

declare(strict_types=1);

namespace WonderNetwork\SlimKernel\Cli\Logging;

use SplStack;

final class ConsoleIoStack {
/**
* @var SplStack<ConsoleIo>
*/
private SplStack $stack;

public function __construct() {
$this->stack = new SplStack();
}

public function push(ConsoleIo $consoleIo): void {
$this->stack->push($consoleIo);
}

public function pop(): void {
if (false === $this->stack->isEmpty()) {
$this->stack->pop();
}
}

public function current(): ?ConsoleIo {
if ($this->stack->isEmpty()) {
return null;
}

return $this->stack->top();
}
}
16 changes: 16 additions & 0 deletions src/Cli/Logging/CurrentConsoleInput.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

declare(strict_types=1);

namespace WonderNetwork\SlimKernel\Cli\Logging;

use Symfony\Component\Console\Input\InputInterface;

final readonly class CurrentConsoleInput {
public function __construct(private ConsoleIoStack $stack) {
}

public function currentInput(): ?InputInterface {
return $this->stack->current()?->input;
}
}
16 changes: 16 additions & 0 deletions src/Cli/Logging/CurrentConsoleOutput.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

declare(strict_types=1);

namespace WonderNetwork\SlimKernel\Cli\Logging;

use Symfony\Component\Console\Output\OutputInterface;

final readonly class CurrentConsoleOutput {
public function __construct(private ConsoleIoStack $stack) {
}

public function currentOutput(): ?OutputInterface {
return $this->stack->current()?->output;
}
}
100 changes: 100 additions & 0 deletions src/Cli/Logging/Formatter/ConsoleFormatter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
<?php

namespace WonderNetwork\SlimKernel\Cli\Logging\Formatter;

use Monolog\Formatter\FormatterInterface;
use Monolog\Level;
use Monolog\LogRecord;
use Stringable;
use Symfony\Component\Console\Formatter\OutputFormatter;

/**
* @see https://raw.githubusercontent.com/symfony/symfony/refs/heads/8.0/src/Symfony/Bridge/Monolog/Formatter/ConsoleFormatter.php
*
* Formats incoming records for console output by coloring them depending on log level.
*/
final class ConsoleFormatter implements FormatterInterface {
private const array LEVEL_COLOR_MAP = [
Level::Debug->value => 'fg=white',
Level::Info->value => 'fg=green',
Level::Notice->value => 'fg=blue',
Level::Warning->value => 'fg=cyan',
Level::Error->value => 'fg=yellow',
Level::Critical->value => 'fg=red',
Level::Alert->value => 'fg=red',
Level::Emergency->value => 'fg=white;bg=red',
];

public function formatBatch(array $records): mixed {
foreach ($records as $key => $record) {
$records[$key] = $this->format($record);
}

return $records;
}

public function format(LogRecord $record): string {
$record = $this->replacePlaceHolder($record);

$levelColor = \sprintf('<%s>', self::LEVEL_COLOR_MAP[$record->level->value]);

return \strtr(
"<fg=gray>%datetime% %channel%</> %start_tag%%level_name%%end_tag% %message%\n",
[
'%datetime%' => $record->datetime->format('H:i:s'),
'%start_tag%' => $levelColor,
'%level_name%' => strtolower($record->level->getName()),
'%end_tag%' => '</>',
'%channel%' => $record->channel,
'%message%' => $this->replacePlaceHolder($record)->message,
],
);
}

private function replacePlaceHolder(LogRecord $record): LogRecord {
$message = $record->message;

if (false === \str_contains($message, '{')) {
return $record;
}

$context = $record->context;

$replacements = [];

foreach ($context as $k => $v) {
$v = OutputFormatter::escape($this->dumpData($v));
$replacements['{'.$k.'}'] = \sprintf('<comment>%s</>', $v);
}

return $record->with(message: \strtr($message, $replacements));
}

private function dumpData(mixed $data): string {
if (\is_string($data) || \is_int($data) || \is_float($data) || $data instanceof Stringable) {
return (string) $data;
}

if (null === $data) {
return 'N/A';
}

if (\is_bool($data)) {
return $data ? 'true' : 'false';
}

if (\is_array($data)) {
return \sprintf('array(%d)', \count($data));
}

if (\is_resource($data)) {
return \sprintf('resource(%d)', \get_resource_type($data));
}

if (\is_object($data)) {
return \sprintf('object(%d)', $data::class);
}

return \sprintf('unknown(%s)', \get_debug_type($data));
}
}
Loading