4
4
5
5
namespace Luzrain \PHPStreamServer \Internal \Logger ;
6
6
7
+ use Amp \ByteStream \WritableResourceStream ;
7
8
use Psr \Log \LoggerInterface ;
8
9
use Psr \Log \LoggerTrait ;
10
+ use function Amp \async ;
9
11
10
12
/**
11
13
* @internal
16
18
17
19
private const DEFAULT_JSON_FLAGS = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION | JSON_INVALID_UTF8_SUBSTITUTE | JSON_PARTIAL_OUTPUT_ON_ERROR ;
18
20
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
+
19
34
/**
20
- * @var resource
35
+ * @var $resource $ resource
21
36
*/
22
- private mixed $ stream ;
23
-
24
- public function __construct ()
37
+ public function __construct ($ resource = STDERR )
25
38
{
26
- $ this ->stream = STDERR ;
39
+ $ this ->stream = new WritableResourceStream ( $ resource ) ;
27
40
}
28
41
29
42
public function log (mixed $ level , string |\Stringable $ message , array $ context = []): void
30
43
{
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
+ });
33
49
}
34
50
35
51
private function format (string $ level , string $ message , array $ context ): string
@@ -44,9 +60,10 @@ private function format(string $level, string $message, array $context): string
44
60
$ message = \strtr ($ message , $ replacements );
45
61
}
46
62
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 ) : '' ;
49
66
50
- return $ formattedMessage . $ formattedContext ;
67
+ return \rtrim ( \sprintf ( " %s %s \t <color;fg=green>%s</> \t %s %s " , $ date , $ level , ' phpss ' , $ message , $ context )) ;
51
68
}
52
69
}
0 commit comments