Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,16 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Added

- Structured logging via [PSR-3](https://www.php-fig.org/psr/psr-3/): `ClientBuilder::logger()` injects any `Psr\Log\LoggerInterface`; no logger is used by default. Emits `client.initialized` (INFO, once), `http.request.sent` / `http.response.received` (DEBUG, per attempt), and `http.request.failed` (ERROR, transport failures only). Query and JSON-body secrets (`api_key`, `api_secret`, `token`, `password`) are always redacted. Request/response bodies are excluded by default; opt in with `ClientBuilder::logBodies(true)`.

### Changed

- **Behavior change:** the connection-pool configuration is no longer written to PHP's `error_log()` at client construction. That information is now available only through an injected PSR-3 logger, as the `client.initialized` event. If you relied on the old `error_log` line, inject a logger via `->logger(...)` instead.

## [9.0.0] - 2026-07-15

OpenAPI regeneration for optional query parameters ([FEEDS-1651](https://linear.app/stream/issue/FEEDS-1651), [#54](https://github.com/GetStream/getstream-php/pull/54)).
Expand Down
34 changes: 34 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,40 @@ Per-call `curl` overrides replace (do not merge with) the client-level `curl` op

**Escape hatch:** Passing your own client via `->httpClient($mine)` skips all 4 knobs; your client is used as-is.

## Logging

The SDK emits structured events through a [PSR-3](https://www.php-fig.org/psr/psr-3/) `Psr\Log\LoggerInterface`. No logger is injected by default (`Psr\Log\NullLogger`, a no-op); pass your own via `->logger(...)`:

```php
$client = (new GetStream\ClientBuilder())
->apiKey($apiKey)
->apiSecret($apiSecret)
->logger($myPsr3Logger)
->build();
```

Events emitted:

| Event | Level | When |
|---|---|---|
| `client.initialized` | INFO | Once, at construction |
| `http.request.sent` | DEBUG | Before each HTTP attempt |
| `http.response.received` | DEBUG | After any HTTP response, including 4xx/5xx (status codes are data, not a failure) |
| `http.request.failed` | ERROR | Transport failure only (connection reset, timeout, DNS failure, TLS handshake failure) — no HTTP response was received |

The SDK never sets the logger's minimum level; that's the caller's responsibility.

**Bodies are not logged by default.** Enable with `->logBodies(true)`; this emits one WARN at construction and adds (key-redacted) `http.request.body` / `http.response.body` fields to the DEBUG events. Query values for `api_key`, `api_secret`, `token` and top-level JSON body keys `api_secret`, `token`, `password` are always redacted (case-insensitive for query values), whether or not body logging is on. No headers are ever logged.

```php
$client = (new GetStream\ClientBuilder())
->apiKey($apiKey)
->apiSecret($apiSecret)
->logger($myPsr3Logger)
->logBodies(true)
->build();
```

## Code Generation

Generate API methods from OpenAPI spec:
Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"ext-json": "*",
"firebase/php-jwt": "^7.0",
"guzzlehttp/guzzle": "^7.0",
"psr/log": "^3.0",
"vlucas/phpdotenv": "^5.0"
},
"require-dev": {
Expand Down
52 changes: 51 additions & 1 deletion composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 0 additions & 3 deletions phpunit.xml
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,5 @@
<directory suffix=".php">src</directory>
</include>
</source>
<php>
<const name="PHPUNIT_RUNNING" value="true"/>
</php>
</phpunit>

78 changes: 58 additions & 20 deletions src/ClientBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
use GetStream\Http\GuzzleHttpClient;
use GetStream\Http\HttpClientInterface;
use GetStream\Http\PoolConfig;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;

/**
* Builder class for creating GetStream clients with environment variable support.
Expand All @@ -22,6 +24,8 @@ class ClientBuilder
private bool $loadEnv = true;
private ?string $envPath = null;
private PoolConfig $pool;
private ?LoggerInterface $logger = null;
private bool $logBodies = false;

public function __construct()
{
Expand Down Expand Up @@ -112,6 +116,30 @@ public function requestTimeout(int $seconds): self
return $this;
}

/**
* Inject a PSR-3 logger for structured `client.initialized` / `http.request.*` /
* `http.response.*` events. Default when none is set: `Psr\Log\NullLogger` (no-op).
* The SDK never sets the logger's level; that is the caller's responsibility.
*/
public function logger(LoggerInterface $logger): self
{
$this->logger = $logger;

return $this;
}

/**
* Include (key-redacted) request/response bodies in the `http.request.sent` /
* `http.response.received` log events. Off by default. Enabling this emits one
* WARN at construction time.
*/
public function logBodies(bool $on): self
{
$this->logBodies = $on;

return $this;
}

/**
* Disable loading from environment variables.
*/
Expand Down Expand Up @@ -265,41 +293,51 @@ private function getEnvVar(string $name): ?string
/**
* Resolve the HttpClient.
* If the user supplied one via httpClient(), return it as-is (escape hatch).
* Otherwise build a GuzzleHttpClient with the configured PoolConfig and emit the INFO log.
* Otherwise build a GuzzleHttpClient with the configured PoolConfig. Either way,
* emit one `client.initialized` INFO event through the injected PSR-3 logger.
*/
private function resolveHttpClient(): HttpClientInterface
{
$logger = $this->logger ?? new NullLogger();

$user = $this->httpClient;
if ($user !== null) {
$this->logInfo(
'getstream-php connection pool: user_http_client=true (5 knobs not applied)'
);
$logger->info('client.initialized', $this->clientInitializedContext(userHttpClient: true));
$this->warnIfLogBodies($logger);

return $user;
}

$client = new GuzzleHttpClient([], 3, $this->pool);
$client = new GuzzleHttpClient([], 3, $this->pool, $logger, $this->logBodies);

$this->logInfo(sprintf(
'getstream-php connection pool: max_conns_per_host=%d idle_timeout=%ds connect_timeout=%ds request_timeout=%ds user_http_client=false',
$this->pool->maxConnsPerHost,
$this->pool->idleTimeout,
$this->pool->connectTimeout,
$this->pool->requestTimeout,
));
$logger->info('client.initialized', $this->clientInitializedContext(userHttpClient: false));
$this->warnIfLogBodies($logger);

return $client;
}

/**
* Emit one INFO log line via error_log().
* Suppressed under PHPUnit to keep test output clean (PHPUNIT_RUNNING constant is set in phpunit.xml).
*/
private function logInfo(string $message): void
private function warnIfLogBodies(LoggerInterface $logger): void
{
if (defined('PHPUNIT_RUNNING') && PHPUNIT_RUNNING) {
return;
if ($this->logBodies) {
$logger->warning(
'HTTP request/response bodies will be logged. Auth headers and known-secret fields are still redacted, but other sensitive data (messages, PII) may appear in logs. Disable for production.'
);
}
error_log('[INFO] ' . $message);
}

/** @return array<string, scalar> */
private function clientInitializedContext(bool $userHttpClient): array
{
return [
'stream.sdk.name' => 'getstream-php',
'stream.sdk.version' => Constant::VERSION,
'stream.client.max_conns_per_host' => $this->pool->maxConnsPerHost,
'stream.client.idle_timeout_seconds' => $this->pool->idleTimeout,
'stream.client.connect_timeout_seconds' => $this->pool->connectTimeout,
'stream.client.request_timeout_seconds' => $this->pool->requestTimeout,
'stream.client.gzip_enabled' => true,
'stream.client.user_http_client' => $userHttpClient,
'stream.client.log_bodies' => $this->logBodies,
];
}
}
Loading
Loading