在AWS PHP SDK的第2版中,我只需执行以下操作即可设置请求和响应信息的记录:
<?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)
在第3版中,我似乎无法找到解决方案。中间件似乎没有帮助,因为它们只在发送请求之前触发,因此我无法访问响应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似乎乍一看似乎有效。不确定此方法可能存在哪些问题。
答案 0 :(得分:1)
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错误转换为异常。