Files
michaelschiemer/src/Framework/Telemetry
Michael Schiemer fc3d7e6357 feat(Production): Complete production deployment infrastructure
- Add comprehensive health check system with multiple endpoints
- Add Prometheus metrics endpoint
- Add production logging configurations (5 strategies)
- Add complete deployment documentation suite:
  * QUICKSTART.md - 30-minute deployment guide
  * DEPLOYMENT_CHECKLIST.md - Printable verification checklist
  * DEPLOYMENT_WORKFLOW.md - Complete deployment lifecycle
  * PRODUCTION_DEPLOYMENT.md - Comprehensive technical reference
  * production-logging.md - Logging configuration guide
  * ANSIBLE_DEPLOYMENT.md - Infrastructure as Code automation
  * README.md - Navigation hub
  * DEPLOYMENT_SUMMARY.md - Executive summary
- Add deployment scripts and automation
- Add DEPLOYMENT_PLAN.md - Concrete plan for immediate deployment
- Update README with production-ready features

All production infrastructure is now complete and ready for deployment.
2025-10-25 19:18:37 +02:00
..

Telemetry Module

The Telemetry module provides a unified system for collecting, processing, and exporting telemetry data from the application. It supports tracing operations, recording metrics, and capturing events.

Core Components

UnifiedTelemetryService

The main entry point for the telemetry system. It provides methods for:

  • Starting and ending operations
  • Recording metrics
  • Recording events
  • Tracing function execution
// Get the telemetry service from the container
$telemetry = $container->get(UnifiedTelemetryService::class);

// Start an operation
$operation = $telemetry->startOperation('process_order', 'business', [
    'order_id' => $orderId,
    'customer_id' => $customerId
]);

try {
    // Perform the operation
    $result = processOrder($orderId);
    
    // Record a metric
    $telemetry->recordMetric('order_value', $result->getTotalValue(), 'EUR');
    
    // Record an event
    $telemetry->recordEvent('order_processed', [
        'order_id' => $orderId,
        'status' => 'success'
    ]);
    
    // End the operation
    $operation->end('success');
    
    return $result;
} catch (\Throwable $e) {
    // Mark the operation as failed
    $operation->fail($e->getMessage());
    
    // Re-throw the exception
    throw $e;
}

Trace Method

For simpler cases, you can use the trace method to automatically handle operation lifecycle:

$result = $telemetry->trace(
    'process_order',
    'business',
    function() use ($orderId) {
        return processOrder($orderId);
    },
    [
        'order_id' => $orderId,
        'customer_id' => $customerId
    ]
);

Data Model

Operation

Represents a discrete operation or span of work in the application. Operations can be nested to create a trace.

$operation = $telemetry->startOperation('name', 'type', ['attribute' => 'value']);
$operation->addAttribute('key', 'value');
$operation->end('success');

Metric

Represents a measurable value. Metrics can be counters, gauges, or histograms.

$telemetry->recordMetric('name', 42.0, 'unit', ['attribute' => 'value']);

Event

Represents a discrete occurrence. Events can have different severity levels.

$telemetry->recordEvent('name', ['attribute' => 'value'], 'info');

Exporters

Telemetry data can be exported to various backends using exporters.

FileExporter

Exports telemetry data to log files in JSON Lines format.

$exporter = new FileExporter('/path/to/logs');
$telemetry->addExporter($exporter);

PrometheusExporter

Exports metrics in Prometheus format for scraping.

$exporter = new PrometheusExporter();
$telemetry->addExporter($exporter);

// In your metrics endpoint:
$metricsOutput = $exporter->getMetricsOutput();
return new Response($metricsOutput, 200, ['Content-Type' => 'text/plain']);

Integration Components

TelemetryHttpMiddleware

Middleware for tracing HTTP requests.

// Register in your middleware stack
$middlewareManager->add(TelemetryHttpMiddleware::class);

TelemetryDatabaseMiddleware

Middleware for tracing database queries.

// Register in your database middleware pipeline
$pipeline->add(new TelemetryDatabaseMiddleware($telemetryService));

Cache Telemetry

Cache telemetry is available through the MetricsDecoratedCache which provides comprehensive cache operation tracking and performance monitoring. For custom telemetry needs, implement a custom cache decorator using the current batched Cache interface.

PerformanceCollectorAdapter

Adapter that implements PerformanceCollectorInterface and forwards calls to the telemetry service.

// Register in your container
$container->singleton(PerformanceCollectorInterface::class, function ($c) {
    return new PerformanceCollectorAdapter(
        $c->get(UnifiedTelemetryService::class),
        $c->get(EnhancedPerformanceCollector::class)
    );
});

Configuration

The telemetry system can be configured using the TelemetryConfig class:

$config = new TelemetryConfig(
    serviceName: 'my-service',
    serviceVersion: '1.0.0',
    environment: 'production',
    enabled: true,
    samplingRatio: 0.1, // Sample 10% of operations
    exporters: [
        'file' => new ExporterConfig('/path/to/logs', 'file'),
        'prometheus' => new ExporterConfig('http://localhost:9090', 'http')
    ],
    resourceAttributes: [
        'deployment.environment' => 'production',
        'service.instance.id' => 'instance-1'
    ]
);

Best Practices

  1. Use meaningful operation names: Choose descriptive names that indicate what the operation does.
  2. Add relevant attributes: Include attributes that help identify the context of the operation.
  3. Use appropriate operation types: Use consistent types like 'http', 'database', 'cache', 'business', etc.
  4. Handle errors properly: Always mark operations as failed when exceptions occur.
  5. Use the trace method for simple cases: For simple operations, use the trace method to automatically handle the operation lifecycle.
  6. Be mindful of sensitive data: Avoid including sensitive data in attributes or event details.
  7. Use sampling in production: In high-volume production environments, use sampling to reduce the amount of telemetry data collected.