如何使用Guzzle 6记录所有API调用 [英] How do you log all API calls using Guzzle 6

查看:367
本文介绍了如何使用Guzzle 6记录所有API调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用性能良好的guzzle 6,但是在记录所有api调用方面我迷路了.我想简单地记录时间,从会话,URL和与API调用有关的其他任何常规相关信息中登录的用户.我似乎找不到关于Guzzle 6的任何文档,仅涉及Guzzle 3(在此文档中,他们更改了日志记录addSubscriber调用).这是我当前的API调用方式:

I'm trying to use guzzle 6 which works fine but I'm lost when it comes to how to log all the api calls. I would like to simply log timing, logged in user from session, url and any other usual pertinent info that has to do with the API call. I can't seem to find any documentation for Guzzle 6 that refers to this, only guzzle 3 (Where they've changed the logging addSubscriber call). This is how my current API calls are:

$client = new GuzzleHttp\Client(['defaults' => ['verify' => false]]);
$res = $client->get($this->url . '/api/details', ['form_params' => ['file' => $file_id]]);

推荐答案

您可以使用任何通过Guzzle 6实现PSR-3接口的记录器

You can use any logger which implements PSR-3 interface with Guzzle 6

在下面的示例中,我使用Monolog作为记录器和带有MessageFormatter的Guzzle内置中间件.

I used Monolog as logger and builtin middleware of Guzzle with MessageFormatter in below example.

use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\MessageFormatter;
use Monolog\Logger;

$stack = HandlerStack::create();
$stack->push(
    Middleware::log(
        new Logger('Logger'),
        new MessageFormatter('{req_body} - {res_body}')
    )
);
$client = new \GuzzleHttp\Client(
    [
        'base_uri' => 'http://httpbin.org',
        'handler' => $stack,
    ]
);

echo (string) $client->get('ip')->getBody();

关于日志中间件和消息格式化程序的详细信息尚未得到很好的记录.但是您可以检查列表可以在MessageFormatter中使用哪些变量

The details about the log middleware and message formatter has not well documented yet. But you can check the list which variables you can use in MessageFormatter

还有一个 guzzle-logmiddleware ,它允许您自定义格式化程序等.

Also there is a guzzle-logmiddleware which allows you to customize formatter etc.

这篇关于如何使用Guzzle 6记录所有API调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆