1
0
mirror of synced 2024-11-21 21:06:07 +03:00

Merge pull request #163 from oxy-coach/v5

Add logger for request/response logging to http client
This commit is contained in:
Andrey 2023-04-06 12:38:51 +03:00 committed by GitHub
commit 1901f1a81d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
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);
@ -128,6 +136,8 @@ class Client
list($statusCode, $responseBody) = $this->checkResponse($curlHandler, $method);
$this->logResponse($responseBody, $statusCode);
return new ApiResponse($statusCode, $responseBody);
}
@ -166,6 +176,16 @@ class Client
$this->options = $options;
}
/**
* Set logger
*
* @param LoggerInterface|null $logger
*/
public function setLogger($logger = null)
{
$this->logger = $logger;
}
/**
* @param $curlHandler
* @param $method
@ -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);
}
}