Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Debug Logging prototype #570

Closed
wants to merge 13 commits into from
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
"guzzlehttp/guzzle": "^7.4.5",
"guzzlehttp/psr7": "^2.4.5",
"psr/http-message": "^1.1||^2.0",
"psr/cache": "^2.0||^3.0"
"psr/cache": "^2.0||^3.0",
"psr/log": "^3.0"
},
"require-dev": {
"guzzlehttp/promises": "^2.0",
Expand Down
23 changes: 22 additions & 1 deletion src/ApplicationDefaultCredentials.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,14 @@
use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\HttpHandler\HttpClientCache;
use Google\Auth\HttpHandler\HttpHandlerFactory;
use Google\Auth\Logger\StdOutLogger;
use Google\Auth\Middleware\AuthTokenMiddleware;
use Google\Auth\Middleware\ProxyAuthTokenMiddleware;
use Google\Auth\Subscriber\AuthTokenSubscriber;
use GuzzleHttp\Client;
use InvalidArgumentException;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Log\LoggerInterface;

/**
* ApplicationDefaultCredentials obtains the default credentials for
Expand Down Expand Up @@ -69,6 +71,8 @@
*/
class ApplicationDefaultCredentials
{
private const SDK_DEBUG_FLAG = 'GOOGLE_SDK_DEBUG_LOGGING';

/**
* @deprecated
*
Expand Down Expand Up @@ -157,7 +161,7 @@ public static function getCredentials(
CacheItemPoolInterface $cache = null,
$quotaProject = null,
$defaultScope = null,
string $universeDomain = null
string $universeDomain = null,
) {
$creds = null;
$jsonKey = CredentialsLoader::fromEnv()
Expand Down Expand Up @@ -353,4 +357,21 @@ private static function onGce(

return (new GCECache($gceCacheConfig, $cache))->onGce($httpHandler);
}

/**
* A function that returns the default logger if the GOOGLE_SDK_DEBUG_LOGGING
* environment variable is set. Returns null if not.
*
* @return null|LoggerInterface
*/
public static function getDefaultLogger(): null|LoggerInterface
{
$loggingFlag = (string)getenv(self::SDK_DEBUG_FLAG);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit

Suggested change
$loggingFlag = (string)getenv(self::SDK_DEBUG_FLAG);
$loggingFlag = (string) getenv(self::SDK_DEBUG_FLAG);

I've added a CS rule for this in GoogleCloudPlatform/php-tools#149


if (!$loggingFlag || strtolower($loggingFlag) !== 'true') {
return null;
}

return new StdOutLogger();
}
}
46 changes: 44 additions & 2 deletions src/HttpHandler/Guzzle6HttpHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,23 +16,34 @@
*/
namespace Google\Auth\HttpHandler;

use Google\Auth\Logger\LogEvent;
use Google\Auth\Logger\LoggingTrait;
use GuzzleHttp\ClientInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Log\LoggerInterface;

class Guzzle6HttpHandler
{
use LoggingTrait;

/**
* @var ClientInterface
*/
private $client;

/**
* @var LoggerInterface
*/
private $logger;

/**
* @param ClientInterface $client
*/
public function __construct(ClientInterface $client)
public function __construct(ClientInterface $client, LoggerInterface $logger = null)
{
$this->client = $client;
$this->logger = $logger;
}

/**
Expand All @@ -57,6 +68,37 @@ public function __invoke(RequestInterface $request, array $options = [])
*/
public function async(RequestInterface $request, array $options = [])
{
return $this->client->sendAsync($request, $options);
$requestEvent = null;

if ($this->logger) {
$requestEvent = new LogEvent();

$requestEvent->method = $request->getMethod();
$requestEvent->url = $request->getUri()->__toString();
$requestEvent->headers = $request->getHeaders();
$requestEvent->payload = $request->getBody()->getContents();
$requestEvent->retryAttempt = $options['retryAttempt'] ?? null;
$requestEvent->serviceName = $options['serviceName'];
$requestEvent->clientId = $options['clientId'];
$requestEvent->requestId = spl_object_id($request);

$this->logRequest($requestEvent);
}

return $this->client->sendAsync($request, $options)->then(function (ResponseInterface $response) use ($requestEvent) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit, but this could be attached only when the logger is defined, which would look a little more cleaner. e.g.

$promise = $this->client->sendAsync($request, $options);
if ($this->logger) {
    $promise->then( /** ... */);
}
return $promise;

if ($this->logger) {
$responseEvent = new LogEvent($requestEvent->timestamp);

$responseEvent->headers = $response->getHeaders();
$responseEvent->payload = json_decode($response->getBody()->getContents()) ?: null;
$responseEvent->status = $response->getStatusCode();
$responseEvent->clientId = $requestEvent->clientId;
$responseEvent->requestId = $requestEvent->requestId;

$this->logResponse($responseEvent);
}

return $response;
});
}
}
13 changes: 10 additions & 3 deletions src/HttpHandler/HttpHandlerFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,13 @@
*/
namespace Google\Auth\HttpHandler;

use Google\Auth\ApplicationDefaultCredentials;
use GuzzleHttp\BodySummarizer;
use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use Psr\Log\LoggerInterface;

class HttpHandlerFactory
{
Expand All @@ -31,7 +33,7 @@ class HttpHandlerFactory
* @return Guzzle6HttpHandler|Guzzle7HttpHandler
* @throws \Exception
*/
public static function build(ClientInterface $client = null)
public static function build(ClientInterface $client = null, ?LoggerInterface $logger = null)
{
if (is_null($client)) {
$stack = null;
Expand All @@ -42,6 +44,7 @@ public static function build(ClientInterface $client = null)
$stack->remove('http_errors');
$stack->unshift(Middleware::httpErrors($bodySummarizer), 'http_errors');
}

$client = new Client(['handler' => $stack]);
}

Expand All @@ -52,11 +55,15 @@ public static function build(ClientInterface $client = null)
$version = (int) substr(ClientInterface::VERSION, 0, 1);
}

if (!$logger) {
$logger = ApplicationDefaultCredentials::getDefaultLogger();
}
Comment on lines +58 to +60
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit (suggestion) - make this one line

Suggested change
if (!$logger) {
$logger = ApplicationDefaultCredentials::getDefaultLogger();
}
$logger = $logger ?? ApplicationDefaultCredentials::getDefaultLogger();


switch ($version) {
case 6:
return new Guzzle6HttpHandler($client);
return new Guzzle6HttpHandler($client, $logger);
case 7:
return new Guzzle7HttpHandler($client);
return new Guzzle7HttpHandler($client, $logger);
default:
throw new \Exception('Version not supported');
}
Expand Down
120 changes: 120 additions & 0 deletions src/Logger/LogEvent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
<?php
/**
* Copyright 2024 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Google\Auth\Logger;

class LogEvent
{
/**
* Timestamp in format RFC3339 representing when this event ocurred
*
* @var null|string
*/
public null|string $timestamp = null;

/**
* Rest method type
*
* @var null|string
*/
public null|string $method = null;

/**
* URL representing the rest URL endpoint
*
* @var null|string
*/
public null|string $url = null;

/**
* An array that contains the headers for the response or request
*
* @var null|array<mixed>
*/
public null|array $headers = null;

/**
* An array representation of JSON for the response or request
*
* @var null|string
*/
public null|string $payload = null;

/**
* Status code for REST or gRPC methods
*
* @var null|int|string
*/
public null|int|string $status = null;

/**
* The latency in miliseconds
*
* @var null|int
*/
public null|int $latency = null;

/**
* The retry attempt number
*
* @var null|int
*/
public null|int $retryAttempt = null;

/**
* The name of the gRPC method being called
*
* @var null|string
*/
public null|string $rpcName = null;

/**
* The Service Name of the gRPC
*
* @var null|string $serviceName
*/
public null|string $serviceName;

/**
* The Client Id for easy trace
*
* @var int $clientId
*/
public int $clientId;

/**
* The Request id for easy trace
*
* @var int $requestId;
*/
public int $requestId;

/**
* Creates an object with all the fields required for logging
*
* @param null|string $startTime (Optional) Parameter to calculate the latency
*/
public function __construct(null|string $startTime = null)
{
$this->timestamp = date(DATE_RFC3339);

if ($startTime) {
// We should check for false in here
$this->latency = (int)strtotime($this->timestamp) - (int)strtotime($startTime);
}
}
}
Loading