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

1.1.0 2026-01-03 18:53 UTC

This package is auto-updated.

Last update: 2026-01-03 18:59:07 UTC


README

gemvc_header_for_github

GEMVC APM TraceKit Provider

License: MIT PHP Version

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 extending AbstractApm (used by ApmFactory)
  • TraceKitModel - Alternative APM provider implementation extending AbstractApm (with additional methods like addEvent())
  • TraceKitToolkit - Client-side integration and management class extending AbstractApmToolkit
  • OpenTelemetry OTLP JSON Format - Sends traces in standard OpenTelemetry format
  • Non-blocking Trace Sending - Uses GEMVC's AsyncApiCall for 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:

  1. Config array (passed to constructor/init) - Highest priority
  2. Provider-specific env vars (TRACEKIT_*) - Medium priority
  3. Unified APM env vars (APM_*) - Lower priority
  4. 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 .env file
  • Tests the connection to verify everything works

Setup Options:

  1. Easy Register - Automated registration with email verification
  2. 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:

  1. Framework Initialization - The framework creates a TraceKitProvider instance via ApmFactory::create()
  2. Root Trace Creation - A root span is automatically created for each HTTP request
  3. Span Management - Child spans are created for database queries, controller operations, etc.
  4. 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:

  1. Welcome Banner - Displays TraceKit features and welcome message
  2. Configuration Detection - Checks for existing TraceKit configuration
    • If found, offers to reconfigure, test connection, or exit
  3. 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
  4. Service Name Setup - Prompts for unique service name with validation
  5. Automatic Configuration - Updates .env file with:
    • TRACEKIT_API_KEY - Your API key
    • TRACEKIT_SERVICE_NAME - Your service name
    • APM_NAME="TraceKit" - Provider name
    • APM_ENABLED="true" - Enable APM
  6. Connection Test - Verifies API key and connection to TraceKit service
  7. 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 enabled
  • startTrace(string $operationName, array $attributes = [], bool $forceSample = false): array - Start a root trace (span). $forceSample = true forces tracing regardless of sample rate (used for errors)
  • startSpan(string $operationName, array $attributes = [], int $kind = self::SPAN_KIND_INTERNAL): array - Start a child span. $kind can be SPAN_KIND_SERVER, SPAN_KIND_CLIENT, SPAN_KIND_INTERNAL, etc.
  • endSpan(array $spanData, array $finalAttributes = [], ?string $status = self::STATUS_OK): void - End a span. $status can be STATUS_OK or STATUS_ERROR
  • recordException(array $spanData, \Throwable $exception): array - Record an exception on a span. Auto-creates trace if no root span exists
  • flush(): void - Send traces to TraceKit service (non-blocking)
  • getTraceId(): ?string - Get current trace ID (inherited from AbstractApm)

Static Methods:

  • getCurrentInstance(): ?TraceKitProvider - Get the current active instance
  • clearCurrentInstance(): 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 service
  • verifyCode(string $sessionId, string $code): JsonResponse - Verify email and get API key
  • getStatus(): JsonResponse - Check integration status
  • sendHeartbeatAsync(string $status, array $metadata): void - Send asynchronous heartbeat
  • getMetrics(string $window): JsonResponse - Get service metrics
  • getAlertsSummary(): JsonResponse - Get alerts overview
  • createWebhook(string $name, string $url, array $events, bool $enabled): JsonResponse - Create webhook

For complete API documentation, see the GEMVC APM Contracts README.

πŸ”„ Related Packages

🌐 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 tracing
  • APM_TRACE_DB_QUERY - Enable/disable database query tracing
  • APM_TRACE_REQUEST_BODY - Enable/disable request body tracing
  • APM_API_KEY - Unified API key (works for all providers)

TraceKit-Specific Variables

  • TRACEKIT_API_KEY - TraceKit API key (or use APM_API_KEY)
  • TRACEKIT_SERVICE_NAME - Service name for traces
  • TRACEKIT_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