46 lines
1.1 KiB
PHP
46 lines
1.1 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\ApiLog;
|
|
use Illuminate\Http\Client\Response;
|
|
use Throwable;
|
|
|
|
class ApiLogger
|
|
{
|
|
/**
|
|
* Execute an HTTP request and log it to api_logs.
|
|
*
|
|
* The callable must return an Illuminate\Http\Client\Response.
|
|
* Exceptions are logged and re-thrown so the caller handles them.
|
|
*
|
|
* @param callable(): Response $request
|
|
*/
|
|
public function send(string $service, string $method, string $url, callable $request): Response
|
|
{
|
|
$start = microtime(true);
|
|
$statusCode = null;
|
|
$error = null;
|
|
|
|
try {
|
|
$response = $request();
|
|
$statusCode = $response->status();
|
|
|
|
return $response;
|
|
} catch (Throwable $e) {
|
|
$error = $e->getMessage();
|
|
|
|
throw $e;
|
|
} finally {
|
|
ApiLog::create([
|
|
'service' => $service,
|
|
'method' => strtoupper($method),
|
|
'url' => $url,
|
|
'status_code' => $statusCode,
|
|
'duration_ms' => (int) round((microtime(true) - $start) * 1000),
|
|
'error' => $error,
|
|
]);
|
|
}
|
|
}
|
|
}
|