Skip to content

Commit

Permalink
SimpleLogger implementation now can colorize output and works asynchr…
Browse files Browse the repository at this point in the history
…onously.
  • Loading branch information
luzrain committed Oct 7, 2024
1 parent 033e5de commit 054a7ca
Showing 1 changed file with 27 additions and 10 deletions.
37 changes: 27 additions & 10 deletions src/Internal/Logger/SimpleLogger.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@

namespace Luzrain\PHPStreamServer\Internal\Logger;

use Amp\ByteStream\WritableResourceStream;
use Psr\Log\LoggerInterface;
use Psr\Log\LoggerTrait;
use function Amp\async;

/**
* @internal
Expand All @@ -16,20 +18,34 @@

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

private const LEVELS_COLOR_MAP = [
'debug' => '<color;fg=15>DEBUG</>',
'info' => '<color;fg=116>INFO</>',
'notice' => '<color;fg=38>NOTICE</>',
'warning' => '<color;fg=yellow>WARNING</>',
'error' => '<color;fg=red>ERROR</>',
'critical' => '<color;fg=red>CRITICAL</>',
'alert' => '<color;fg=red>ALERT</>',
'emergency' => '<color;bg=red>EMERGENCY</>',
];

private WritableResourceStream $stream;

/**
* @var resource
* @var $resource $resource
*/
private mixed $stream;

public function __construct()
public function __construct($resource = STDERR)
{
$this->stream = STDERR;
$this->stream = new WritableResourceStream($resource);
}

public function log(mixed $level, string|\Stringable $message, array $context = []): void
{
$message = $this->format((string) $level, (string) $message, $context);
\fwrite($this->stream, $message . PHP_EOL);
$formattedMessage = $this->format((string) $level, (string) $message, $context);

async(function () use ($formattedMessage) {
$this->stream->write($formattedMessage. PHP_EOL);
});
}

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

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

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

0 comments on commit 054a7ca

Please sign in to comment.