60 lines
1.8 KiB
PHP
60 lines
1.8 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Services;
|
|
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Log;
|
|
use Illuminate\Support\Str;
|
|
|
|
/**
|
|
* NotFoundLogger
|
|
*
|
|
* Logs 404 and 500 error events to dedicated log channels so they can
|
|
* be tracked, aggregated and used to create redirect rules later.
|
|
*
|
|
* 404 → logged to 'not_found' channel (see config/logging.php daily driver)
|
|
* 500 → logged to default channel with correlation ID
|
|
*/
|
|
final class NotFoundLogger
|
|
{
|
|
/**
|
|
* Log a 404 hit: URL, referrer, user-agent, user ID.
|
|
*/
|
|
public function log404(Request $request): void
|
|
{
|
|
Log::channel(config('logging.not_found_channel', 'daily'))->info('404 Not Found', [
|
|
'url' => $request->fullUrl(),
|
|
'method' => $request->method(),
|
|
'referrer' => $request->header('Referer') ?? '(direct)',
|
|
'user_agent' => $request->userAgent(),
|
|
'user_id' => $request->user()?->id,
|
|
'ip' => $request->ip(),
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* Log a 500 server error with a generated correlation ID.
|
|
* Returns the correlation ID so it can be shown on the error page.
|
|
*/
|
|
public function log500(\Throwable $e, Request $request): string
|
|
{
|
|
$correlationId = strtoupper(Str::random(8));
|
|
|
|
Log::error('500 Server Error [' . $correlationId . ']', [
|
|
'correlation_id' => $correlationId,
|
|
'url' => $request->fullUrl(),
|
|
'method' => $request->method(),
|
|
'exception' => get_class($e),
|
|
'message' => $e->getMessage(),
|
|
'file' => $e->getFile(),
|
|
'line' => $e->getLine(),
|
|
'user_id' => $request->user()?->id,
|
|
'ip' => $request->ip(),
|
|
]);
|
|
|
|
return $correlationId;
|
|
}
|
|
}
|