4

在 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() 现在返回不正确的值,因为此处理程序不会引发 aws-php-sdk 预期会发生的 404 异常。乍一看,其他一些简单的请求(例如上传到 S3)似乎可以正常工作。不知道这种方法还有什么问题。

4

1 回答 1

2

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 错误转换为异常。

于 2015-11-16T18:56:21.717 回答