parli / json-logger
PSR-3 JSON 日志记录器
1.0.1
2021-10-04 17:38 UTC
Requires
- php: ^8.0
- psr/log: ^1.0 || ^2.0 || ^3.0
Requires (Dev)
- phpstan/phpstan: ^0.12.46
- phpstan/phpstan-phpunit: ^0.12.16
- phpstan/phpstan-strict-rules: ^0.12.5
- phpunit/phpunit: ^9.3
- squizlabs/php_codesniffer: ^3.5
This package is auto-updated.
Last update: 2024-09-09 13:03:32 UTC
README
PSR-3 JSON 格式化器。该工具输出一种围绕 Datadog 日志系统设计的格式,使用他们的预定义属性来构建结构。
用法
此库仅格式化日志,并不写入日志。必须与另一个PSR-3一起使用,后者负责将日志写入有用的位置。(对于容器化环境部署,我们使用 stdout
。)
$writer = new \SomePsr3Logger(); $logger = new \Parli\JsonLogger\JsonLogger($writer); // ... $logger->error('Error message {info}', [ 'info' => $someMoreInfo, 'exception' => $someThrowable, ]);
注意:日志写入者不会接收到此库接收到的 $context
。此库在将完全格式化的 JSON 字符串传递给日志写入者之前,将上下文插值到 JSON 消息中。
异常日志记录
此库会在 $context
的 exception
键中查找 Throwable
,按照PSR-3第1.3节。如果找到,它将自动填充错误属性,以与 Datadog 的日志显示系统集成。
建议您始终将捕获的异常传递给日志记录器的 $context
(例如 ->error('...', ['exception' => $e])
)。另外,建议您不要进行额外的日志插值。
示例
try { // ... } catch (Throwable $e) { $logger->error('Caught exception in worker with input {input}', [ 'input' => $input, 'exception' => $e, ]); }
反例
// Do NOT do this: try { // ... } catch (Throwable $e) { $logger->error('Caught exception in worker with input {input} - {message}: {trace}', [ 'input' => $input, 'message' => $e->getMessage(), 'trace' => $e->getTraceAsString(), 'exception' => $e, ]); }