Skip to content

Commit 054a7ca

Browse files
committed
SimpleLogger implementation now can colorize output and works asynchronously.
1 parent 033e5de commit 054a7ca

File tree

1 file changed

+27
-10
lines changed

1 file changed

+27
-10
lines changed

src/Internal/Logger/SimpleLogger.php

Lines changed: 27 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,10 @@
44

55
namespace Luzrain\PHPStreamServer\Internal\Logger;
66

7+
use Amp\ByteStream\WritableResourceStream;
78
use Psr\Log\LoggerInterface;
89
use Psr\Log\LoggerTrait;
10+
use function Amp\async;
911

1012
/**
1113
* @internal
@@ -16,20 +18,34 @@
1618

1719
private const DEFAULT_JSON_FLAGS = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION | JSON_INVALID_UTF8_SUBSTITUTE | JSON_PARTIAL_OUTPUT_ON_ERROR;
1820

21+
private const LEVELS_COLOR_MAP = [
22+
'debug' => '<color;fg=15>DEBUG</>',
23+
'info' => '<color;fg=116>INFO</>',
24+
'notice' => '<color;fg=38>NOTICE</>',
25+
'warning' => '<color;fg=yellow>WARNING</>',
26+
'error' => '<color;fg=red>ERROR</>',
27+
'critical' => '<color;fg=red>CRITICAL</>',
28+
'alert' => '<color;fg=red>ALERT</>',
29+
'emergency' => '<color;bg=red>EMERGENCY</>',
30+
];
31+
32+
private WritableResourceStream $stream;
33+
1934
/**
20-
* @var resource
35+
* @var $resource $resource
2136
*/
22-
private mixed $stream;
23-
24-
public function __construct()
37+
public function __construct($resource = STDERR)
2538
{
26-
$this->stream = STDERR;
39+
$this->stream = new WritableResourceStream($resource);
2740
}
2841

2942
public function log(mixed $level, string|\Stringable $message, array $context = []): void
3043
{
31-
$message = $this->format((string) $level, (string) $message, $context);
32-
\fwrite($this->stream, $message . PHP_EOL);
44+
$formattedMessage = $this->format((string) $level, (string) $message, $context);
45+
46+
async(function () use ($formattedMessage) {
47+
$this->stream->write($formattedMessage. PHP_EOL);
48+
});
3349
}
3450

3551
private function format(string $level, string $message, array $context): string
@@ -44,9 +60,10 @@ private function format(string $level, string $message, array $context): string
4460
$message = \strtr($message, $replacements);
4561
}
4662

47-
$formattedMessage = \sprintf('%s [%s] %s', \date(\DateTimeInterface::RFC3339), $level, $message);
48-
$formattedContext = $context !== [] ? ' ' . \json_encode($context, self::DEFAULT_JSON_FLAGS) : '';
63+
$date = \date('Y-m-d H:i:s');
64+
$level = self::LEVELS_COLOR_MAP[$level] ?? $level;
65+
$context = $context !== [] ? '' . \json_encode($context, self::DEFAULT_JSON_FLAGS) : '';
4966

50-
return $formattedMessage . $formattedContext;
67+
return \rtrim(\sprintf("%s %s\t<color;fg=green>%s</>\t%s %s", $date, $level, 'phpss', $message, $context));
5168
}
5269
}

0 commit comments

Comments
 (0)