PHP SDK
GitHubOfficial PHP SDK for LogWard with strict types, automatic batching, retry logic, and Laravel/Symfony/PSR-15 middleware.
Installation
Requires PHP 8.1 or higher
bash
composer require logward/sdk-phpQuick Start
php
<?php
use LogWard\SDK\LogWardClient;
use LogWard\SDK\Models\LogWardClientOptions;
$client = new LogWardClient(new LogWardClientOptions(
apiUrl: 'http://localhost:8080',
apiKey: 'lp_your_api_key_here',
));
// Send logs
$client->info('api-gateway', 'Server started', ['port' => 3000]);
$client->error('database', 'Connection failed', new PDOException('Timeout'));
// Shutdown is auto-handled via register_shutdown_functionFeatures
- ✅ Automatic batching with configurable size and interval
- ✅ Retry logic with exponential backoff
- ✅ Circuit breaker pattern for fault tolerance
- ✅ Max buffer size with drop policy to prevent memory leaks
- ✅ Query API for searching and filtering logs
- ✅ Live tail with Server-Sent Events (SSE)
- ✅ Trace ID context for distributed tracing
- ✅ Global metadata added to all logs
- ✅ Structured error serialization
- ✅ Internal metrics (logs sent, errors, latency)
- ✅ Laravel, Symfony & PSR-15 middleware
- ✅ Full PHP 8.1+ support with strict types and enums
Configuration
php
<?php
$client = new LogWardClient(new LogWardClientOptions(
// Required
apiUrl: 'http://localhost:8080',
apiKey: 'lp_your_api_key',
// Optional - Performance
batchSize: 100, // Max logs per batch (default: 100)
batchInterval: 5000, // Flush interval in ms (default: 5000)
maxBufferSize: 10000, // Max logs in buffer (default: 10000)
// Optional - Reliability
maxRetries: 3, // Max retry attempts (default: 3)
retryDelay: 1000, // Initial retry delay in ms (default: 1000)
circuitBreakerThreshold: 5, // Failures before circuit opens (default: 5)
circuitBreakerTimeout: 60000, // Circuit reset timeout in ms (default: 60000)
// Optional - Metadata
globalMetadata: [ // Added to all logs
'environment' => 'production',
'version' => '1.0.0'
],
// Optional - Debug
debug: false // Enable debug logging (default: false)
));Logging Methods
Basic Logging
php
<?php
// Log levels: debug, info, warn, error, critical
$client->debug('service-name', 'Debug message', ['detail' => 'value']);
$client->info('api-gateway', 'Request received', ['method' => 'GET', 'path' => '/users']);
$client->warn('cache', 'Cache miss', ['key' => 'user:123']);
$client->error('database', 'Query failed', ['query' => 'SELECT *']);
$client->critical('system', 'Out of memory', ['used' => '95%']);Scoped Trace ID
php
<?php
// All logs within this scope have the same trace_id
$client->withTraceId('550e8400-e29b-41d4-a716-446655440000', function() use ($client) {
$client->info('api', 'Processing request');
$client->info('db', 'Query executed');
});Middleware Integration
Laravel Middleware
php
<?php
// app/Http/Kernel.php
protected $middleware = [
// ... other middleware
\LogWard\SDK\Middleware\LaravelLogWardMiddleware::class,
];
// config/services.php
'logward' => [
'api_url' => env('LOGWARD_API_URL', 'http://localhost:8080'),
'api_key' => env('LOGWARD_API_KEY'),
],Symfony Event Subscriber
php
<?php
// config/services.yaml
services:
LogWard\SDK\Middleware\SymfonyLogWardSubscriber:
arguments:
$client: '@LogWard\SDK\LogWardClient'
tags:
- { name: kernel.event_subscriber }
LogWard\SDK\LogWardClient:
arguments:
$options: !service
class: LogWard\SDK\Models\LogWardClientOptions
arguments:
$apiUrl: '%env(LOGWARD_API_URL)%'
$apiKey: '%env(LOGWARD_API_KEY)%'PSR-15 Middleware
php
<?php
use LogWard\SDK\Middleware\Psr15LogWardMiddleware;
$middleware = new Psr15LogWardMiddleware($client);
// Add to your PSR-15 middleware stack
$app->pipe($middleware);Query API
php
<?php
// Search logs
$result = $client->query([
'service' => 'api-gateway',
'level' => 'error',
'from' => '2025-01-15T00:00:00Z',
'to' => '2025-01-15T23:59:59Z',
'q' => 'timeout', // Full-text search
'limit' => 100
]);
echo "Found {$result['total']} error logs\n";
foreach ($result['logs'] as $log) {
echo "[{$log['time']}] {$log['message']}\n";
}Best Practices
1. Automatic Shutdown Handling
The SDK automatically registers a shutdown function to flush
logs on script termination. No manual cleanup needed!
2. Use Enums for Log Levels
PHP 8.1+ enums provide type safety. Use
LogLevel::ERROR instead of strings where possible.3. Leverage Middleware
Framework middleware automatically logs all requests with
response times, status codes, and trace IDs.