前不久对接了一个海康企业安全平台,
调试时发现需要查看请求及响应日志。
上网找了很久发现可以在GuzzleHttp中加入日志
上代码
namespace app\service;
use GuzzleHttp\Client;
use GuzzleHttp\TransferStats;
use support\Log;
use support\Redis;
use support\Response;
class HikvisionBase
{
private $app_key;
private $app_secret;
private $base_url;
public $client = null;
private $base_headers;
private $http_method = 'POST';
private $accept = '*/*';
private $content_type = 'application/json';
private $headers_no_cal = [
'accept',
'date',
'host',
'server',
'connection',
'content-md5',
'content-type',
'content-length',
'transfer-encoding',
'content-encoding',
'x-application-context',
'x-ca-signature',
'x-ca-signature-headers',
];
protected $redis_key;
public function __construct($app_key, $app_secret, $base_url)
{
$this->app_key = $app_key;
$this->app_secret = $app_secret;
$this->base_url = $base_url;
$this->redis_key = 'dts_hikvision_access_token_' . $app_key;
if ($this->client == null) {
$this->client = new Client([
'base_uri' => $this->base_url,
'verify' => false,
'http_errors' => false,
'timeout' => 6,
'on_stats' => function(TransferStats $stats){
//这里可以获取到请求对象
$request = $stats->getRequest();
$logsContent["REQUEST"] = [
"PATH" => $request->getUri()->getPath(),
"METHOD" => $request->getMethod(),
"QUERY" => $request->getUri()->getQuery(),
"BODY" => json_decode($request->getBody(), true)
];
Log::info('请求日志::', $logsContent["REQUEST"]);
//判断是否有正常的响应对象
if ($stats->hasResponse()) {
//这里可以获取到响应对象
$response = $stats->getResponse();
$logsContent["RESPONSE"] = [
"STATUS_CODE" => $response->getStatusCode(),
"BODY" => json_decode($response->getBody(), true)
];
} else { //这里一般都是网络发生错误,常见的有CURL错误码
if ($stats->getHandlerErrorData() instanceof \Exception) {
$error = $stats->getHandlerErrorData()->getMessage();
} else {
$error = $stats->getHandlerErrorData();
}
$logsContent["RESPONSE"] = [
"ERROR" => $error
];
}
Log::info('响应日志::',$logsContent["RESPONSE"]);
}
]);
}
$this->init_base_headers();
}
}