thegrimmchester/opa-helper
Composer 安装命令:
composer require thegrimmchester/opa-helper
包简介
PHP helper for OpenProfilingAgent - chunking and flushing
README 文档
README
PHP helper library for OpenProfilingAgent - provides programmatic control to create spans, chunk and flush them to the Unix socket or TCP/IP endpoint. Uses a background non-blocking writer via register_shutdown_function for reliability on process exit.
Features
Client Class
The Client class provides a high-level API for creating and managing spans, with automatic chunking and flushing capabilities.
Span Management
- Create Spans: Programmatically create spans with custom names and tags
- Start/End Spans: Manage span lifecycle with automatic timing
- Span Hierarchy: Set parent-child relationships between spans
- Active Span Tracking: Track multiple active spans simultaneously
Chunking & Flushing
- Automatic Chunking: Spans are automatically chunked when buffer size or span count limits are reached
- Configurable Limits: Set maximum chunk size (bytes) and maximum spans per chunk
- Circular Buffer: Maintains a configurable circular buffer of recent spans for history queries
- Automatic Flush on Shutdown: Ensures all spans are flushed when the process exits
- Manual Flush: Manually trigger flushing of buffered spans
Transport Support
- Unix Socket: Connect to OpenProfilingAgent via Unix domain socket (default:
/var/run/opa.sock) - TCP/IP: Connect via TCP/IP using
host:portformat - Retry Logic: Automatic retry mechanism with configurable attempts
- Non-blocking: Uses non-blocking writes with timeout handling
Extension Integration
- Seamless Integration: Works with the PHP extension when available
- Graceful Fallback: Falls back to pure PHP implementation when extension is unavailable
- Unified API: Same API works with or without the extension
Metadata Management
- Organization & Project IDs: Automatic inclusion of organization and project identifiers
- Service Information: Configure service name for span identification
- Language Metadata: Automatic detection and inclusion of PHP version
- Framework Support: Optional framework name and version tracking
Span Enhancements
- Tags: Add custom tags to spans for filtering and grouping
- Annotations: Add timestamped annotations to spans
- Variable Dumping: Dump variables to spans with file and line information
- Dump Storage: Store variable dumps within spans for debugging
Profiling Control
- Enable/Disable: Programmatically enable or disable profiling
- Status Check: Check if profiling is currently enabled
History & Querying
- Span History: Query recent spans from the circular buffer
- Filtering: Filter spans by trace_id, service, or name
- Configurable Limit: Set maximum number of results returned
ErrorTracker Class
The ErrorTracker class provides automatic error and exception tracking.
Automatic Error Tracking
- Error Handler: Automatically captures all PHP errors (E_ERROR, E_WARNING, E_NOTICE, etc.)
- Exception Handler: Automatically captures all uncaught exceptions
- Fatal Error Handler: Captures fatal errors via shutdown function
- Stack Trace Capture: Automatically captures stack traces for errors and exceptions
Error Information
- Error Type: Categorizes errors by type (Error, Warning, Notice, etc.)
- Error Message: Captures the error message
- File & Line: Records the file and line number where the error occurred
- Fingerprinting: Generates unique fingerprints for error grouping
Integration Options
- Extension Integration: Uses
opa_track_error()when extension is available - Client Fallback: Falls back to sending errors as spans via Client when extension unavailable
- Manual Tracking: Manually track errors with custom information
Error Types Supported
- E_ERROR, E_WARNING, E_PARSE, E_NOTICE
- E_CORE_ERROR, E_CORE_WARNING
- E_COMPILE_ERROR, E_COMPILE_WARNING
- E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE
- E_STRICT, E_RECOVERABLE_ERROR
- E_DEPRECATED, E_USER_DEPRECATED
Installation
composer require thegrimmchester/opa-helper
Requirements
- PHP >= 8.0
- OpenProfilingAgent extension (optional, library works without it)
Usage
Basic Client Usage
use OpenProfilingAgent\Client; // Create a client instance $client = new Client( sock: '/var/run/opa.sock', // Unix socket path or 'host:port' for TCP/IP maxChunkBytes: 256 * 1024, // Max chunk size in bytes maxChunkSpan: 200, // Max spans per chunk circularCap: 5000, // Circular buffer capacity organizationId: 'my-org', projectId: 'my-project', service: 'my-service', framework: 'Symfony', frameworkVersion: '7.0' ); // Create and start a span $span = $client->createSpan('database-query', ['db.type' => 'mysql']); // ... do work ... $client->endSpan($span); // Or use the extension-compatible API $spanId = $client->startSpan('api-call', ['http.method' => 'GET']); // ... do work ... $client->endSpanById($spanId);
Adding Tags and Annotations
// Add tags to a span $client->addTag($spanId, 'user.id', '12345'); $client->addTag($spanId, 'http.status_code', '200'); // Add annotations $client->addAnnotation($spanId, 'Cache miss occurred'); $client->addAnnotation($spanId, 'Database connection established', $timestamp);
Variable Dumping
// Dump variables to the current span $client->dump($variable1, $variable2, $variable3);
Span Hierarchy
$parentSpan = $client->createSpan('parent-operation'); $childSpan = $client->createSpan('child-operation'); $client->setParent($childSpan['span_id'], $parentSpan['span_id']);
Profiling Control
// Enable profiling $client->enable(); // Disable profiling $client->disable(); // Check status if ($client->isEnabled()) { // Profiling is active }
Querying History
// Get recent spans $recentSpans = $client->getHistory(limit: 50); // Filter spans $filteredSpans = $client->getHistory( limit: 100, filter: [ 'service' => 'my-service', 'name' => 'database-query' ] );
Error Tracking
use OpenProfilingAgent\ErrorTracker; use OpenProfilingAgent\Client; // Create client (optional, for fallback when extension unavailable) $client = new Client(); // Register error tracking (automatic) ErrorTracker::register($client); // Or set client separately ErrorTracker::setClient($client); ErrorTracker::register(); // Manually track an error ErrorTracker::track( errorType: 'CustomError', message: 'Something went wrong', file: __FILE__, line: __LINE__, stackTrace: debug_backtrace() );
TCP/IP Transport
// Connect via TCP/IP instead of Unix socket $client = new Client(sock: '127.0.0.1:8080'); // Or just port (defaults to localhost) $client = new Client(sock: '8080');
Configuration
Client Constructor Parameters
sock(string): Unix socket path orhost:portfor TCP/IP (default:/var/run/opa.sock)maxChunkBytes(int): Maximum chunk size in bytes before flushing (default: 256KB)maxChunkSpan(int): Maximum number of spans per chunk (default: 200)circularCap(int): Circular buffer capacity for history (default: 5000)organizationId(string|null): Organization identifier (default:'default-org')projectId(string|null): Project identifier (default:'default-project')service(string|null): Service name (default:'php-app')language(string|null): Language name (default:'php')languageVersion(string|null): Language version (auto-detected from PHP_VERSION if null)framework(string|null): Framework name (default: empty string)frameworkVersion(string|null): Framework version (default: empty string)
Architecture
Chunking Strategy
Spans are buffered in memory and automatically flushed when:
- Buffer size exceeds
maxChunkBytes - Number of spans exceeds
maxChunkSpan - Process shutdown (via
register_shutdown_function)
Chunks are sent with:
- Unique
chunk_idfor grouping - Sequential
chunk_seqfor ordering chunk_doneflag to mark the last span in a chunk
Extension Compatibility
The library provides a unified API that works with or without the PHP extension:
- When extension is available: Uses native extension functions for better performance
- When extension is unavailable: Falls back to pure PHP implementation
- Same API works in both scenarios
Error Tracking Flow
- Error/Exception occurs
- Handler captures error information
- If extension available: Uses
opa_track_error() - If extension unavailable: Creates error span via Client
- Error is sent to OpenProfilingAgent
License
See LICENSE file for details.
统计信息
- 总下载量: 0
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 0
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: Unknown
- 更新时间: 2025-12-08