From 1965138bb3e78544f3f98eb0bf0c6a94ac85ca1f Mon Sep 17 00:00:00 2001 From: Luca Patera Date: Mon, 30 Oct 2023 22:50:43 +0100 Subject: [PATCH] Add a custom monolog formatter for Nutgram --- resources/views/logging/request.blade.php | 8 ++++ resources/views/logging/response.blade.php | 8 ++++ src/Log/NutgramFormatter.php | 43 ++++++++++++++++++++++ src/NutgramServiceProvider.php | 1 + 4 files changed, 60 insertions(+) create mode 100644 resources/views/logging/request.blade.php create mode 100644 resources/views/logging/response.blade.php create mode 100644 src/Log/NutgramFormatter.php diff --git a/resources/views/logging/request.blade.php b/resources/views/logging/request.blade.php new file mode 100644 index 0000000..26295b9 --- /dev/null +++ b/resources/views/logging/request.blade.php @@ -0,0 +1,8 @@ +
+
+ {{$time}} + {{$message}} + {{$endpoint}} +
+
{{$content}}
+
diff --git a/resources/views/logging/response.blade.php b/resources/views/logging/response.blade.php new file mode 100644 index 0000000..f082e8a --- /dev/null +++ b/resources/views/logging/response.blade.php @@ -0,0 +1,8 @@ +
+
+ {{$time}} + {{$message}} +
+
{{$response}}
+
+
diff --git a/src/Log/NutgramFormatter.php b/src/Log/NutgramFormatter.php new file mode 100644 index 0000000..9ddfb19 --- /dev/null +++ b/src/Log/NutgramFormatter.php @@ -0,0 +1,43 @@ +context['type'] === 'request' ? $this->formatRequest($record) : $this->formatResponse($record); + } + + public function formatBatch(array $records): void + { + array_walk($records, [$this, 'format']); + } + + public function formatRequest(LogRecord $record): void + { + $content = json_encode($record->context['content'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + + render(view('logging::request', [ + 'time' => $record->datetime->format('Y-m-d H:i:s'), + 'message' => $record->message, + 'endpoint' => $record->context['endpoint'], + 'content' => $content, + ])); + } + + public function formatResponse(LogRecord $record): void + { + $response = json_encode($record->context['response'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + + render(view('logging::response', [ + 'time' => $record->datetime->format('Y-m-d H:i:s'), + 'message' => $record->message, + 'response' => $response, + ])); + } +} diff --git a/src/NutgramServiceProvider.php b/src/NutgramServiceProvider.php index c814173..35ac4d8 100644 --- a/src/NutgramServiceProvider.php +++ b/src/NutgramServiceProvider.php @@ -86,6 +86,7 @@ public function boot(): void { if ($this->app->runningInConsole()) { $this->loadViewsFrom(__DIR__.'/../resources/views/terminal', 'terminal'); + $this->loadViewsFrom(__DIR__.'/../resources/views/logging', 'logging'); $this->commands([ Console\RunCommand::class,