AWS PHP SDK v3.中的响应日志记录


Response logging in AWS PHP SDK v3

在AWS PHP SDK的v2中,我只需执行以下操作就可以设置请求和响应信息的日志记录:

<?php
use Monolog'Logger;
use Guzzle'Log'MonologLogAdapter;
use Guzzle'Plugin'Log'LogPlugin;
use Aws'S3'S3Client;
$monolog = new Logger('main');
$monolog_adapter = new MonologLogAdapter($monolog);
$log_plugin = new LogPlugin($monolog_adapter);
$s3_client = S3Client::factory(['region' => 'us-east-1']);
$s3_client->addSubscriber($log_plugin);
var_dump($s3_client->doesObjectExist('my-bucket', 'object-that-doesnt-exist'));
# This is the log entry I want in the v3 version:
# [2015-10-30 14:47:20] main.ERROR: myhostname aws-sdk-php2/2.8.20 Guzzle/3.9.3 curl/7.43.0 PHP/5.5.23 - [2015-10-30T14:47:20+00:00] "HEAD /my-bucket/object-that-doesnt-exist HTTP/1.1" 404  ...
# bool(false)

在v3中,我似乎找不到解决方案。中间件似乎没有帮助,因为它们只在发送请求之前启动,因此我无法访问响应HTTP代码。

Guzzle v6在其中间件中内置了这一功能,但我不知道如何让它与aws-php-sdk一起工作。https://github.com/guzzle/guzzle/blob/master/src/Middleware.php#L180

我得到的最接近的是:

<?php
use Monolog'Logger;
use GuzzleHttp'MessageFormatter;
use GuzzleHttp'Middleware;
use GuzzleHttp'HandlerStack;
use Aws'S3'S3Client;
$monolog = new Logger('main');
$guzzle_formatter = new MessageFormatter(MessageFormatter::CLF);
$guzzle_log_middleware = Middleware::log($monolog, $guzzle_formatter);
$guzzle_stack = HandlerStack::create();
$guzzle_stack->push($guzzle_log_middleware);
$s3_client = new S3Client([
    'region' => 'us-east-1',
    'version' => '2006-03-01',
    'http_handler' => $guzzle_stack,
]);
var_dump($s3_client->doesObjectExist('my-bucket', 'object-that-doesnt-exist'));
# [2015-10-30 15:10:12] main.INFO: myhostname aws-sdk-php/3.9.2 - [30/Oct/2015:15:10:12 +0000] "HEAD /my-bucket/object-that-doesnt-exist HTTP/1.1" 404  [] []
# bool(true)

然而,当日志记录工作时,doesObjectExist()现在返回了不正确的值,因为该处理程序没有为404抛出异常,aws-php-sdk预计会发生这种情况。其他一些简单的请求,比如上传到S3,乍一看似乎有效。不确定此方法在其他地方可能存在问题。

SDK中使用的处理程序与Guzzle中使用的有点不同。您正在正确地创建一个Guzzle处理程序,要将其传递到SDK中,您需要创建一个适配器,如下所示:

<?php
use Aws'Handler'GuzzleV6'GuzzleHandler;
use Aws'S3'S3Client;
use Monolog'Logger;
use GuzzleHttp'Client;
use GuzzleHttp'MessageFormatter;
use GuzzleHttp'Middleware;
use GuzzleHttp'HandlerStack;
$guzzle_stack = HandlerStack::create();
$guzzle_stack->push(Middleware::log(
    new Logger('main'), 
    new MessageFormatter(MessageFormatter::CLF)
));
$handler = new GuzzleHandler(new Client(['handler' => $guzzle_stack]));
$s3_client = new S3Client([
    'region' => 'us-east-1',
    'version' => '2006-03-01',
    'http_handler' => $handler,
]);
var_dump($s3_client->doesObjectExist('my-bucket', 'object-that-doesnt-exist'));

GuzzleHandler对象将HTTP错误转换为异常。

使用aws/aws-sdk php 3.212.7,如@giaour所示注册自定义记录器对我来说不起作用。

配置现在支持debug密钥:

$s3_client = new S3Client([
    'region' => 'us-east-1',
    'version' => '2006-03-01',
    'debug' => true,
]);

这显示传输的数据,但不显示使用的URL。