Skip to content

Instantly share code, notes, and snippets.

@ismail1432
Created February 12, 2023 08:57
Show Gist options
  • Save ismail1432/75b7ffca622ec72b0b8c73cad019cb31 to your computer and use it in GitHub Desktop.
Save ismail1432/75b7ffca622ec72b0b8c73cad019cb31 to your computer and use it in GitHub Desktop.
# services.yaml
services:
    _defaults:
        autowire: true
        autoconfigure: true
        bind:
            $statusCodes: [400, 500]
            $logLevel: 'info'
// 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);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment