*/ private array $ctx; /** * @param string $logFile * @param array $ctx */ public function __construct(string $logFile, array $ctx = []) { $this->logFile = $logFile; $this->ctx = $ctx; } /** * @param string $event * @param array $data */ public function logEvent(string $event, array $data = []): void { $payload = array_merge(['ts' => gmdate('c'), 'event' => $event], $this->ctx, $data); $payload = $this->normalize($payload); $json = json_encode($payload, JSON_UNESCAPED_SLASHES); if ($json === false) { $json = json_encode([ 'ts' => gmdate('c'), 'event' => 'log_error', 'error' => json_last_error_msg(), ], JSON_UNESCAPED_SLASHES); } @file_put_contents($this->logFile, $json . "\n", FILE_APPEND | LOCK_EX); } private function normalize(mixed $value): mixed { if (is_array($value)) { $out = []; foreach ($value as $k => $v) { $out[$k] = $this->normalize($v); } return $out; } if (is_bool($value) || is_int($value) || is_float($value) || $value === null) { return $value; } $str = (string)$value; return preg_replace('/[\x00-\x1F\x7F]/', '_', $str); } }