Skip to content

Commit

Permalink
Improve Log and Error Handling
Browse files Browse the repository at this point in the history
  • Loading branch information
danieltrolezi committed Sep 27, 2024
1 parent b8bec4c commit c0d2734
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
55 changes: 55 additions & 0 deletions app/Providers/AppServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,16 @@

use App\Guards\JwtGuard;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Console\Events\CommandStarting;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
use Laravel\Octane\Events\RequestHandled;
use Laravel\Octane\Events\RequestReceived;
use Spatie\Health\Checks\Checks\DatabaseCheck;
use Spatie\Health\Checks\Checks\EnvironmentCheck;
use Spatie\Health\Checks\Checks\RedisCheck;
Expand All @@ -33,6 +38,8 @@ public function boot(): void
$this->setHealthCheck();
$this->setJwtGuard();
$this->setRateLimit();
$this->setLogContext();
$this->setRequestLogging();
}

private function setHealthCheck(): void
Expand Down Expand Up @@ -84,4 +91,52 @@ private function setRateLimit(): void
return Limit::perMinute(config('app.rate_limit.discord'));
});
}

private function setLogContext(): void
{
$common = [
'app' => Str::slug(config('app.name')),
'env' => config('app.env'),
];

$this->app['events']->listen(RequestReceived::class, function (RequestReceived $event) use ($common) {
$requestId = $event->request->header('X-Request-ID', (string) Str::uuid());

Log::shareContext(array_merge($common, [
'request_id' => $requestId
]));
});

$this->app['events']->listen(CommandStarting::class, function (CommandStarting $event) use ($common) {
Log::shareContext(array_merge($common, [
'command' => $event->command,
]));
});
}

private function setRequestLogging(): void
{
$this->app['events']->listen(RequestHandled::class, function (RequestHandled $event) {
$responseContent = '{***}';
$protectedRoutes = ['/api/auth/login'];

if (!in_array($event->request->getPathInfo(), $protectedRoutes)) {
$responseContent = strlen($event->response->getContent()) > 500
? substr($event->response->getContent(), 0, 120) . '...'
: $event->response->getContent();
}

Log::info('Request & Response', [
'method' => $event->request->method(),
'url' => $event->request->fullUrl(),
'status' => $event->response->getStatusCode(),
'ip' => $event->request->ip(),
'client_ip' => $event->request->getClientIp(),
'user_id' => $event->request->user()?->id,
'user_agent' => $event->request->userAgent(),
'referer' => $event->request->header('Referer'),
'response' => $responseContent,
]);
});
}
}
10 changes: 10 additions & 0 deletions bootstrap/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpKernel\Exception\HttpException;

return Application::configure(basePath: dirname(__DIR__))
Expand All @@ -26,6 +27,15 @@
$middleware->throttleWithRedis();
})
->withExceptions(function (Exceptions $exceptions) {
$exceptions->report(function (Exception $e) {
Log::error($e->getMessage(), [
'exception' => get_class($e),
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => $e->getTraceAsString()
]);
})->stop();

$exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) {
if ($request->is('api/*')) {
return true;
Expand Down

0 comments on commit c0d2734

Please sign in to comment.