Skip to content

Commit

Permalink
Add a custom monolog formatter for Nutgram
Browse files Browse the repository at this point in the history
  • Loading branch information
Lukasss93 committed Oct 30, 2023
1 parent 368884f commit 1965138
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 0 deletions.
8 changes: 8 additions & 0 deletions resources/views/logging/request.blade.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<div class="mb-1">
<div>
<span class="px-1 bg-yellow-500 text-black">{{$time}}</span>
<span class="mx-1">{{$message}}</span>
<span class="px-1 bg-green-500 text-black">{{$endpoint}}</span>
</div>
<div class="text-gray-500">{{$content}}</div>
</div>
8 changes: 8 additions & 0 deletions resources/views/logging/response.blade.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<div class="mb-1">
<div>
<span class="px-1 bg-yellow-500 text-black">{{$time}}</span>
<span class="mx-1">{{$message}}</span>
</div>
<div class="text-gray-500">{{$response}}</div>
<div class="content-repeat-['.']"></div>
</div>
43 changes: 43 additions & 0 deletions src/Log/NutgramFormatter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

namespace Nutgram\Laravel\Log;

use Monolog\Formatter\FormatterInterface;
use Monolog\LogRecord;
use function Termwind\{render};

class NutgramFormatter implements FormatterInterface
{
public function format(LogRecord $record): void
{
$record->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,
]));
}
}
1 change: 1 addition & 0 deletions src/NutgramServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down

0 comments on commit 1965138

Please sign in to comment.