webclient/ext-log

PSR-18 HTTP 客户端日志扩展

v1.0.1 2020-11-04 09:40 UTC

This package is auto-updated.

Last update: 2024-09-04 18:59:22 UTC


README

Latest Stable Version Total Downloads License PHP

webclient/ext-log

PSR-18 HTTP 客户端的日志装饰器。

安装

安装此包,您最喜欢的 psr-3 实现 和您最喜欢的 psr-18 实现

composer require webclient/ext-log:^1.0

使用

<?php

use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Log\LoggerInterface;
use Webclient\Extension\Log\Client;

/** 
 * @var ClientInterface $client 
 * @var LoggerInterface $logger 
 */
$http = new Client($client, $logger);

/** @var RequestInterface $request */
$response = $http->sendRequest($request);

自定义请求 ID

您可以为日志中的请求 ID 实现 \Webclient\Extension\Log\IdGenerator\IdGenerator

<?php

use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Log\LoggerInterface;
use Webclient\Extension\Log\Client;
use Webclient\Extension\Log\IdGenerator\IdGenerator;

/** 
 * @var ClientInterface $client 
 * @var LoggerInterface $logger 
 * @var IdGenerator $idGenerator 
 */
$http = new Client($client, $logger, $idGenerator);

/** @var RequestInterface $request */
$response = $http->sendRequest($request);

自定义日志输出

您可以为日志中的请求/响应输出实现 \Webclient\Extension\Log\Formatter\Formatter

<?php

use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Log\LoggerInterface;
use Webclient\Extension\Log\Client;
use Webclient\Extension\Log\Formatter\Formatter;

/** 
 * @var ClientInterface $client 
 * @var LoggerInterface $logger 
 * @var Formatter $formatter 
 */
$http = new Client($client, $logger, null, $formatter);

/** @var RequestInterface $request */
$response = $http->sendRequest($request);

日志级别

您可以设置您的日志级别

<?php

use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use Webclient\Extension\Log\Client;

/** 
 * @var ClientInterface $client 
 * @var LoggerInterface $logger 
 */
$http = new Client(
    $client,
    $logger,
    null,
    null,
    LogLevel::INFO, // Request log level
    LogLevel::INFO, // Info responses (status codes 1xx)
    LogLevel::INFO, // Success responses (status codes 2xx)
    LogLevel::INFO, // Redirect responses (status codes 3xx)
    LogLevel::EMERGENCY, // Client error responses (status codes 4xx)
    LogLevel::ERROR, // Server error responses (status codes 5xx)
    LogLevel::WARNING // Base HTTP client exceptions
);

/** @var RequestInterface $request */
$response = $http->sendRequest($request);