gemvc / apm-tracekit
TraceKit APM provider for GEMVC framework
Installs: 8
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 0
Forks: 0
Open Issues: 0
pkg:composer/gemvc/apm-tracekit
Requires
- php: >=8.2
- gemvc/apm-contracts: ^1.0
- gemvc/library: ^5.2
Requires (Dev)
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^10.5
README
GEMVC APM TraceKit Provider
TraceKit APM provider implementation for GEMVC framework. This package implements the GEMVC APM Contracts interface, providing distributed tracing and performance monitoring for GEMVC applications.
β¬οΈ Installation
composer require gemvc/apm-tracekit
This package automatically installs gemvc/apm-contracts as a dependency, which provides the base interfaces and abstract classes.
π― Architecture
This package is built on top of the GEMVC APM Contracts package:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β gemvc/apm-contracts β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
β β ApmInterface β β AbstractApm β β ApmFactory β β
β β (Contract) β β (Base) β β (Universal) β β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
β ββββββββββββββββββββ ββββββββββββββββββββ β
β βApmToolkitInterfaceβ βAbstractApmToolkitβ β
β β (Contract) β β (Base) β β
β ββββββββββββββββββββ ββββββββββββββββββββ β
ββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββ
β implements/extends
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β gemvc/apm-tracekit β
β ββββββββββββββββββββ ββββββββββββββββββββ β
β β TraceKitProvider β β TraceKitToolkit β β
β β (extends β β (extends β β
β β AbstractApm) β β AbstractApmToolkit) β
β β [Used by Factory]β ββββββββββββββββββββ β
β ββββββββββββββββββββ β
β ββββββββββββββββββββ β
β β TraceKitModel β β
β β (extends β β
β β AbstractApm) β β
β β [Alternative] β β
β ββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Key Components:
TraceKitProvider- Main APM provider class extendingAbstractApm(used byApmFactory)TraceKitModel- Alternative APM provider implementation extendingAbstractApm(with additional methods likeaddEvent())TraceKitToolkit- Client-side integration and management class extendingAbstractApmToolkit- OpenTelemetry OTLP JSON Format - Sends traces in standard OpenTelemetry format
- Non-blocking Trace Sending - Uses GEMVC's
AsyncApiCallfor fire-and-forget trace delivery
π Configuration
Environment Variables
Set in your .env file:
# Core APM Configuration APM_NAME="TraceKit" APM_ENABLED="true" APM_SAMPLE_RATE="1.0" APM_TRACE_RESPONSE="false" APM_TRACE_DB_QUERY="false" APM_TRACE_REQUEST_BODY="false" # TraceKit-Specific Configuration TRACEKIT_API_KEY="your-api-key" TRACEKIT_SERVICE_NAME="your-service-name" TRACEKIT_SAMPLE_RATE="1.0" TRACEKIT_TRACE_RESPONSE="false" TRACEKIT_TRACE_DB_QUERY="false" TRACEKIT_TRACE_REQUEST_BODY="false"
Note: The TraceKit endpoint URL (https://app.tracekit.dev/v1/traces) is pre-configured as a library constant and does not need to be set in your .env file. If you need to override it (e.g., for custom deployments), you can set TRACEKIT_ENDPOINT in your .env file.
Configuration Priority
Configuration values are loaded in the following priority order:
- Config array (passed to constructor/init) - Highest priority
- Provider-specific env vars (
TRACEKIT_*) - Medium priority - Unified APM env vars (
APM_*) - Lower priority - Default values - Lowest priority
Unified API Key Support
You can use either TRACEKIT_API_KEY or the unified APM_API_KEY environment variable:
# Both work the same way TRACEKIT_API_KEY="your-api-key" # or APM_API_KEY="your-api-key"
Quick Setup with CLI Command
The easiest way to configure TraceKit is using the interactive CLI command:
php vendor/bin/tracekit init
This command provides an interactive wizard that:
- Guides you through registration or API key setup
- Handles email verification flow (waits for your input)
- Automatically configures your
.envfile - Tests the connection to verify everything works
Setup Options:
- Easy Register - Automated registration with email verification
- I have API key - Manual entry of existing API key
See the CLI Setup Wizard section below for detailed information.
π‘ Usage
Automatic Integration
Once installed and configured, TraceKit automatically integrates with GEMVC:
- Framework Initialization - The framework creates a
TraceKitProviderinstance viaApmFactory::create() - Root Trace Creation - A root span is automatically created for each HTTP request
- Span Management - Child spans are created for database queries, controller operations, etc.
- Trace Flushing - Traces are automatically sent after the HTTP response (non-blocking)
Manual Span Creation
You can create custom spans in your code:
// Get APM instance from Request $apm = $request->apm; if ($apm !== null && $apm->isEnabled()) { // Start a custom span $span = $apm->startSpan('custom-operation', [ 'custom.attribute' => 'value' ]); try { // Your code here $result = doSomething(); // End span with success $apm->endSpan($span, ['result' => 'success'], \Gemvc\Core\Apm\ApmInterface::STATUS_OK); } catch (\Throwable $e) { // Record exception $apm->recordException($span, $e); $apm->endSpan($span, ['result' => 'error'], \Gemvc\Core\Apm\ApmInterface::STATUS_ERROR); throw $e; } }
Using TraceKit Toolkit
The TraceKitToolkit class provides client-side integration features:
use Gemvc\Core\Apm\Providers\TraceKit\TraceKitToolkit; // Initialize toolkit $toolkit = new TraceKitToolkit(); // Register new service (first-time setup) $response = $toolkit->registerService('admin@example.com', 'My Organization'); if ($response->response_code === 200) { $sessionId = $response->data['session_id']; // User receives verification code via email } // Verify code and activate service $response = $toolkit->verifyCode($sessionId, '123456'); if ($response->response_code === 200) { $apiKey = $response->data['api_key']; // Save to .env: TRACEKIT_API_KEY=$apiKey } // Send periodic health heartbeat (non-blocking) $toolkit->sendHeartbeatAsync('healthy', [ 'memory_usage_mb' => round(memory_get_usage(true) / 1024 / 1024, 2), 'cpu_load' => sys_getloadavg()[0] ?? 0, ]); // Get service metrics $metrics = $toolkit->getMetrics('1h'); // Create webhook for alerts $toolkit->createWebhook( 'production-alerts', 'https://example.com/webhooks/alerts', ['alert.created', 'alert.resolved'], true );
CLI Setup Wizard
The tracekit init command provides an interactive setup wizard for configuring TraceKit:
php vendor/bin/tracekit init
What the wizard does:
- Welcome Banner - Displays TraceKit features and welcome message
- Configuration Detection - Checks for existing TraceKit configuration
- If found, offers to reconfigure, test connection, or exit
- Setup Method Selection:
- Easy Register (Recommended)
- Prompts for email and organization name
- Sends registration request to TraceKit
- Sends verification code to your email
- Waits for you to enter the verification code (CLI does not exit)
- Supports retry logic (max 3 attempts)
- Automatically receives and saves API key
- I have API key
- Prompts for existing API key
- Validates API key format
- Easy Register (Recommended)
- Service Name Setup - Prompts for unique service name with validation
- Automatic Configuration - Updates
.envfile with:TRACEKIT_API_KEY- Your API keyTRACEKIT_SERVICE_NAME- Your service nameAPM_NAME="TraceKit"- Provider nameAPM_ENABLED="true"- Enable APM
- Connection Test - Verifies API key and connection to TraceKit service
- Success Message - Displays confirmation and next steps
Example Flow:
$ php vendor/bin/tracekit init
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Welcome to TraceKit APM Setup Wizard β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Choose setup method:
1. Easy Register (Recommended)
2. I have API key
Enter your choice [1]: 1
Enter your email: admin@example.com
Enter organization name (optional): My Company
Registering service with TraceKit...
Sending registration request... β Done
β Verification code sent to: admin@example.com
Please check your email for the verification code.
Enter verification code from email: 123456
Verifying code... β Verified
β API Key received
β Service registered successfully
Enter service name: my-awesome-service
Saving configuration... β Done
Testing connection... β Connection successful!
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β TraceKit Setup Complete! β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Note: The CLI command is part of the GEMVC framework and uses standard CLI infrastructure (Command, CliBoxShow, ProjectHelper).
β¨ Features
OpenTelemetry OTLP JSON Format
- Standard Format - Uses OpenTelemetry OTLP JSON format for compatibility
- Service Discovery - Automatically includes service name in resource attributes
- Span Hierarchy - Supports parent-child span relationships
- Event Recording - Can record exception events and custom events on spans
Non-Blocking Trace Sending
- Fire-and-Forget - Uses
AsyncApiCall::fireAndForget()for non-blocking delivery - Response First - Ensures HTTP response is sent before trace delivery
- Background Processing - Traces are sent in the background after response completion
- Graceful Degradation - Failures in trace sending don't affect application performance
Span Management
- Stack-Based Context - Simple stack-based span context propagation
- Automatic Sampling - Respects sample rate configuration
- Error Handling - Errors are always traced (forced sampling)
- Span Kinds - Supports OpenTelemetry span kinds (SERVER, CLIENT, INTERNAL, etc.)
π API Reference
TraceKitProvider
Main provider class implementing ApmInterface (used by ApmFactory):
Instance Methods:
init(array $config = []): bool- Initialize provider with configuration (for setup/configuration via CLI/GUI)isEnabled(): bool- Check if tracing is enabledstartTrace(string $operationName, array $attributes = [], bool $forceSample = false): array- Start a root trace (span).$forceSample = trueforces tracing regardless of sample rate (used for errors)startSpan(string $operationName, array $attributes = [], int $kind = self::SPAN_KIND_INTERNAL): array- Start a child span.$kindcan beSPAN_KIND_SERVER,SPAN_KIND_CLIENT,SPAN_KIND_INTERNAL, etc.endSpan(array $spanData, array $finalAttributes = [], ?string $status = self::STATUS_OK): void- End a span.$statuscan beSTATUS_OKorSTATUS_ERRORrecordException(array $spanData, \Throwable $exception): array- Record an exception on a span. Auto-creates trace if no root span existsflush(): void- Send traces to TraceKit service (non-blocking)getTraceId(): ?string- Get current trace ID (inherited fromAbstractApm)
Static Methods:
getCurrentInstance(): ?TraceKitProvider- Get the current active instanceclearCurrentInstance(): void- Clear the current active instance
Note: TraceKitModel is an alternative implementation with additional methods like addEvent(), getSampleRate(), getSampleRatePercent(), and getActiveSpan().
TraceKitToolkit
Client-side integration class implementing ApmToolkitInterface:
registerService(string $email, ?string $organizationName, string $source, array $sourceMetadata): JsonResponse- Register new serviceverifyCode(string $sessionId, string $code): JsonResponse- Verify email and get API keygetStatus(): JsonResponse- Check integration statussendHeartbeatAsync(string $status, array $metadata): void- Send asynchronous heartbeatgetMetrics(string $window): JsonResponse- Get service metricsgetAlertsSummary(): JsonResponse- Get alerts overviewcreateWebhook(string $name, string $url, array $events, bool $enabled): JsonResponse- Create webhook
For complete API documentation, see the GEMVC APM Contracts README.
π Related Packages
- gemvc/apm-contracts - Base APM contracts and interfaces
- gemvc/library - GEMVC core framework
π Environment Variables Reference
Core APM Variables
APM_NAME- APM provider name (must be "TraceKit" for this provider)APM_ENABLED- Enable/disable APM ("true","1","false","0", or boolean)APM_SAMPLE_RATE- Sample rate for traces (0.0 to 1.0, where 1.0 = 100%)APM_TRACE_RESPONSE- Enable/disable response tracingAPM_TRACE_DB_QUERY- Enable/disable database query tracingAPM_TRACE_REQUEST_BODY- Enable/disable request body tracingAPM_API_KEY- Unified API key (works for all providers)
TraceKit-Specific Variables
TRACEKIT_API_KEY- TraceKit API key (or useAPM_API_KEY)TRACEKIT_SERVICE_NAME- Service name for tracesTRACEKIT_ENDPOINT- Override default endpoint URL (optional)TRACEKIT_SAMPLE_RATE- Override sample rate (optional)TRACEKIT_TRACE_RESPONSE- Override response tracing flag (optional)TRACEKIT_TRACE_DB_QUERY- Override DB query tracing flag (optional)TRACEKIT_TRACE_REQUEST_BODY- Override request body tracing flag (optional)
π§ͺ Development
Running Tests
composer test
Code Quality
composer phpstan
βοΈ License
MIT License - see LICENSE file for details.
π₯ Contributing
Contributions are welcome! Please see the GEMVC APM Contracts README for information about the APM provider architecture.
Credits
Part of the GEMVC PHP Framework built for Microservices ecosystem. made with love By Ali Khorsandfard