From 7c6fe569e590791899633c74a5b9dfcf9e5ce2d3 Mon Sep 17 00:00:00 2001 From: Roman Parpalak Date: Mon, 13 May 2024 19:26:07 +0300 Subject: [PATCH] Added logging to NewRelic. --- _include/src/Logger/Logger.php | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/_include/src/Logger/Logger.php b/_include/src/Logger/Logger.php index 594d62f..b47c495 100644 --- a/_include/src/Logger/Logger.php +++ b/_include/src/Logger/Logger.php @@ -149,6 +149,24 @@ public function log($level, string|\Stringable $message, array $context = []): v } $logLine = $this->formatLogLine($level, $pid, $message, $formattedContext, $formattedException); + // Log to NewRelic + if (\extension_loaded('newrelic')) { + if (isset($context['exception']) && $context['exception'] instanceof \Throwable) { + newrelic_notice_error($message, $context['exception']); + } else { + newrelic_notice_error($message); + } + foreach ($contextData as $key => $parameter) { + if (\is_array($parameter)) { + foreach ($parameter as $paramKey => $paramValue) { + $this->setNewRelicParameter('context_' . $key . '_' . $paramKey, $paramValue); + } + } else { + $this->setNewRelicParameter('context_' . $key, $parameter); + } + } + } + // Log to file try { $fh = fopen($this->log_file, 'ab'); @@ -269,4 +287,19 @@ private function getTime(): string { return (new \DateTimeImmutable('now'))->format('Y-m-d H:i:s.u'); } + + private function setNewRelicParameter(string $key, mixed $value): void + { + if (!\extension_loaded('newrelic')) { + return; + } + if (null !== $value && !is_scalar($value)) { + try { + $value = json_encode($value, JSON_THROW_ON_ERROR | \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE); + } catch (\JsonException $e) { + $value = serialize($value); + } + } + newrelic_add_custom_parameter($key, $value); + } }