1
0
mirror of synced 2024-11-22 05:16:07 +03:00

add logger and request/response logging for http client

This commit is contained in:
Vladimir Kolchin 2023-04-06 11:21:04 +03:00
parent 5b91648590
commit b4ec498f32
3 changed files with 77 additions and 0 deletions

View File

@ -11,6 +11,7 @@
namespace RetailCrm;
use Psr\Log\LoggerInterface;
use RetailCrm\Client\ApiVersion3;
use RetailCrm\Client\ApiVersion4;
use RetailCrm\Client\ApiVersion5;
@ -67,4 +68,14 @@ class ApiClient
{
return $this->version;
}
/**
* Set logger
*
* @param LoggerInterface|null $logger
*/
public function setLogger($logger = null)
{
$this->request->setLogger($logger);
}
}

View File

@ -11,6 +11,7 @@
namespace RetailCrm\Client;
use Psr\Log\LoggerInterface;
use RetailCrm\Http\Client;
use RetailCrm\Http\RequestOptions;
@ -142,6 +143,16 @@ abstract class AbstractLoader
return $this->siteCode;
}
/**
* Set logger
*
* @param LoggerInterface|null $logger
*/
public function setLogger($logger)
{
$this->client->setLogger($logger);
}
/**
* Getting the list of available api versions
*

View File

@ -11,6 +11,7 @@
namespace RetailCrm\Http;
use Psr\Log\LoggerInterface;
use RetailCrm\Exception\CurlException;
use RetailCrm\Exception\InvalidJsonException;
use RetailCrm\Exception\LimitException;
@ -34,6 +35,11 @@ class Client
protected $defaultParameters;
protected $options;
/**
* @var LoggerInterface|null $logger
*/
protected $logger;
/**
* Client constructor.
*
@ -116,6 +122,8 @@ class Client
curl_setopt($curlHandler, CURLOPT_HTTPHEADER, $this->options->getHttpHeaders());
}
$this->logRequest($url, $method, $parameters);
if (self::METHOD_POST === $method) {
curl_setopt($curlHandler, CURLOPT_POST, true);
@ -166,6 +174,16 @@ class Client
$this->options = $options;
}
/**
* Set logger
*
* @param LoggerInterface|null $logger
*/
public function setLogger($logger = null)
{
$this->logger = $logger;
}
/**
* @param $curlHandler
* @param $method
@ -178,6 +196,8 @@ class Client
$statusCode = curl_getinfo($curlHandler, CURLINFO_HTTP_CODE);
$contentType = curl_getinfo($curlHandler, CURLINFO_CONTENT_TYPE);
$this->logResponse($responseBody, $statusCode);
if (503 === $statusCode) {
throw new LimitException("Service temporary unavailable");
}
@ -200,4 +220,39 @@ class Client
return [$statusCode, $responseBody];
}
/**
* @param string $url
* @param string $method
* @param array $params
*/
private function logRequest($url, $method, $params)
{
if (null === $this->logger) {
return;
}
$message = 'Send request: ' . $method . ' ' . $url;
if (!empty($params)) {
$message .= ' with params: ' . json_encode($params);
}
$this->logger->info($message);
}
/**
* @param string $responseBody
* @param int $statusCode
*/
private function logResponse($responseBody, $statusCode)
{
if (null === $this->logger) {
return;
}
$message = 'Response with code ' . $statusCode . ' received with body: ' . $responseBody;
$this->logger->info($message);
}
}