traceId = bin2hex(random_bytes(16)); } public function id(): string { return $this->traceId; } public static function elapsedMs(int $startedAt): int { return max(0, (int) floor((hrtime(true) - $startedAt) / 1000000)); } /** * Only a fixed set of numeric and boolean metadata reaches the log. In particular, * arbitrary prompt text, patient identifiers, URLs and credentials are discarded. * * @param array $metrics * @return array */ public function event(string $phase, array $metrics = []): array { $event = [ 'trace_id' => $this->traceId, 'phase' => in_array($phase, self::PHASES, true) ? $phase : 'upstream_done', ]; foreach (self::NUMBER_FIELDS as $field) { if (isset($metrics[$field]) && is_int($metrics[$field])) { $event[$field] = max(0, $metrics[$field]); } } foreach (self::BOOLEAN_FIELDS as $field) { if (isset($metrics[$field]) && is_bool($metrics[$field])) { $event[$field] = $metrics[$field]; } } if (isset($metrics['status']) && in_array($metrics['status'], ['ok', 'error', 'exception', 'disconnected'], true)) { $event['status'] = $metrics['status']; } if (isset($metrics['error_code']) && in_array($metrics['error_code'], self::ERROR_CODES, true)) { $event['error_code'] = $metrics['error_code']; } return $event; } /** @param array $metrics */ public function log(string $phase, array $metrics = []): void { try { Log::info('diagnosis ai assistant timing ' . json_encode($this->event($phase, $metrics))); } catch (\Throwable $ignored) { // Telemetry must never interrupt the clinical request. } } }