Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
11 / 11 |
|
100.00% |
1 / 1 |
CRAP | |
100.00% |
1 / 1 |
| NdJson | |
100.00% |
11 / 11 |
|
100.00% |
1 / 1 |
2 | |
100.00% |
1 / 1 |
| format | |
100.00% |
11 / 11 |
|
100.00% |
1 / 1 |
2 | |||
| 1 | <?php |
| 2 | declare(strict_types=1); |
| 3 | /** |
| 4 | * Pop PHP Framework (https://www.popphp.org/) |
| 5 | * |
| 6 | * @link https://github.com/popphp/popphp-framework |
| 7 | * @author Nick Sagona, III <dev@noladev.com> |
| 8 | * @copyright Copyright (c) 2009-2027 NOLA Interactive, LLC. |
| 9 | * @license https://www.popphp.org/license New BSD License |
| 10 | */ |
| 11 | |
| 12 | /** |
| 13 | * @namespace |
| 14 | */ |
| 15 | namespace Pop\Log\Formatter; |
| 16 | |
| 17 | /** |
| 18 | * NDJSON (JSON Lines) formatter — one self-contained JSON object per line |
| 19 | * |
| 20 | * @category Pop |
| 21 | * @package Pop\Log |
| 22 | * @author Nick Sagona, III <dev@noladev.com> |
| 23 | * @copyright Copyright (c) 2009-2027 NOLA Interactive, LLC. |
| 24 | * @license https://www.popphp.org/license New BSD License |
| 25 | * @version 5.0.0 |
| 26 | */ |
| 27 | class NdJson implements FormatterInterface |
| 28 | { |
| 29 | |
| 30 | /** |
| 31 | * Format a single log entry into a self-contained JSON object |
| 32 | * |
| 33 | * @param string $level |
| 34 | * @param string $message |
| 35 | * @param array $context |
| 36 | * @return string |
| 37 | */ |
| 38 | public function format(string $level, string $message, array $context): string |
| 39 | { |
| 40 | $timestamp = $context['timestamp']; |
| 41 | $name = $context['name']; |
| 42 | unset($context['timestamp'], $context['name'], $context['format']); |
| 43 | |
| 44 | $encoded = json_encode([ |
| 45 | 'timestamp' => $timestamp, |
| 46 | 'level' => $level, |
| 47 | 'name' => $name, |
| 48 | 'message' => $message, |
| 49 | 'context' => (object)$context, |
| 50 | ], JSON_INVALID_UTF8_SUBSTITUTE | JSON_PARTIAL_OUTPUT_ON_ERROR); |
| 51 | |
| 52 | return ($encoded !== false) ? $encoded : '{}'; |
| 53 | } |
| 54 | |
| 55 | } |