# 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

```php
// 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:

```php
$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.

```php
$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.

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

### Event

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

```php
$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.

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

### PrometheusExporter

Exports metrics in Prometheus format for scraping.

```php
$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.

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

### TelemetryDatabaseMiddleware

Middleware for tracing database queries.

```php
// 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.

```php
// 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:

```php
$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.
