// HttpClientLogger.php
namespace App;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpClient\HttpClientTrait;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
use Symfony\Contracts\HttpClient\ResponseStreamInterface;
use Symfony\Component\DependencyInjection\Attribute\AsDecorator;
use Symfony\Component\DependencyInjection\Attribute\MapDecorated;
#[AsDecorator(
decorates: HttpClientInterface::class,
)]
class HttpClientLogger implements HttpClientInterface
{
use HttpClientTrait;
public function __construct(#[MapDecorated] private HttpClientInterface $httpClient, private LoggerInterface $logger, private array $statusCodes, private string $logLevel)
{
}
public function request(string $method, string $url, array $options = []): ResponseInterface
{
$response = $this->httpClient->request($method, $url, $options);
if(in_array($response->getStatusCode(), $this->statusCodes, true)) {
$message = sprintf('Request "%s" to "%s" result to status code "%d" with content "%s"',
$method,
$url,
$response->getStatusCode(),
$response->getContent(false)
);
$context = [
'request_options' => $options,
'response_content' => $response->toArray(false),
];
$this->logger->log($this->logLevel, $message, $context);
}
return $response;
}
public function stream(iterable|ResponseInterface $responses, float $timeout = null): ResponseStreamInterface
{
return $this->httpClient->stream($responses, $timeout);
}
}