PHP code example of azaharizaman / nexus-telemetry

1. Go to this page and download the library: Download azaharizaman/nexus-telemetry library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

azaharizaman / nexus-telemetry example snippets


use Nexus\Telemetry\Services\TelemetryTracker;
use Psr\Log\LoggerInterface;

// Inject dependencies
$tracker = new TelemetryTracker(
    $metricStorage,      // Your storage implementation
    $cardinalityGuard,   // Cardinality protection
    $logger,             // PSR-3 logger
    $tenantContext,      // Optional: multi-tenancy
    $samplingStrategy    // Optional: sampling
);

// Record metrics
$tracker->increment('api.requests', tags: ['endpoint' => '/users']);
$tracker->gauge('memory.usage', 128.5, tags: ['unit' => 'MB']);
$tracker->timing('db.query', 45.2, tags: ['table' => 'users']);
$tracker->histogram('response.size', 1024, tags: ['endpoint' => '/api']);

use Nexus\Telemetry\Services\HealthCheckRunner;
use Nexus\Telemetry\HealthChecks\DatabaseHealthCheck;

// Register health checks
$runner = new HealthCheckRunner($cache, $logger);
$runner->register(new DatabaseHealthCheck($pdo));

// Execute all checks
$results = $runner->runAll();

// Check specific component
$dbHealth = $runner->runCheck('database');
echo $dbHealth->getStatus()->value; // HEALTHY, DEGRADED, OFFLINE, CRITICAL

use Nexus\Telemetry\Traits\MonitoringAwareTrait;

class OrderService
{
    use MonitoringAwareTrait;
    
    public function __construct(TelemetryTrackerInterface $telemetry)
    {
        $this->setTelemetry($telemetry);
    }
    
    public function processOrder(Order $order): void
    {
        // Automatic SLO tracking
        $this->trackOperation('order.process', function() use ($order) {
            // Your business logic
            $this->saveOrder($order);
            $this->notifyCustomer($order);
        }, tags: ['payment_method' => $order->paymentMethod]);
        
        // Manual metrics
        $this->recordIncrement('orders.completed');
        $this->recordGauge('orders.value', $order->total);
    }
}

use Nexus\Telemetry\Services\MetricRetentionService;
use Nexus\Telemetry\Core\TimeBasedRetentionPolicy;

// Create retention policy
$policy = TimeBasedRetentionPolicy::days(30);

$retentionService = new MetricRetentionService(
    $metricStorage,
    $policy,
    $logger
);

// Schedule cleanup (e.g., Laravel)
$schedule->call(function() use ($retentionService) {
    if ($retentionService->needsCleanup(threshold: 10000)) {
        $pruned = $retentionService->pruneExpiredMetrics(batchSize: 1000);
        Log::info("Pruned {$pruned} expired metrics");
    }
})->daily();

increment(string $key, float $value = 1.0, array $tags = []): void
gauge(string $key, float $value, array $tags = []): void
timing(string $key, float $milliseconds, array $tags = []): void
histogram(string $key, float $value, array $tags = []): void

register(HealthCheckInterface $check): void
runAll(): array<HealthCheckResult>
runCheck(string $name): HealthCheckResult

evaluate(\Throwable $exception, array $context = []): void

pruneExpiredMetrics(?int $batchSize = null): int
pruneMetric(string $metricKey): int
getRetentionStats(): array
needsCleanup(int $threshold = 1000): bool

use Nexus\Telemetry\HealthChecks\AbstractHealthCheck;
use Nexus\Telemetry\ValueObjects\HealthStatus;

class RedisHealthCheck extends AbstractHealthCheck
{
    public function __construct(
        private readonly \Redis $redis,
        string $name = 'redis',
        int $priority = 8,
        int $timeoutSeconds = 3,
        int $cacheTtlSeconds = 60
    ) {
        parent::__construct($name, $priority, $timeoutSeconds, $cacheTtlSeconds);
    }
    
    protected function performCheck(): HealthStatus
    {
        $startTime = microtime(true);
        
        // Test connectivity
        $this->redis->ping();
        
        // Test read/write
        $testKey = 'health_check_' . uniqid();
        $this->redis->set($testKey, '1', 10);
        $this->redis->get($testKey);
        $this->redis->del($testKey);
        
        $duration = (microtime(true) - $startTime) * 1000;
        
        return match(true) {
            $duration > 500 => $this->degraded("Slow response: {$duration}ms"),
            default => $this->healthy()
        };
    }
}

use Nexus\Telemetry\Contracts\MetricRetentionInterface;

class TieredRetentionPolicy implements MetricRetentionInterface
{
    public function __construct(
        private readonly array $tiers = [
            'critical.*' => 86400 * 90,  // 90 days
            'business.*' => 86400 * 30,  // 30 days
            'debug.*' => 86400 * 7,      // 7 days
        ],
        private readonly int $defaultPeriod = 86400 * 14
    ) {}
    
    public function getRetentionPeriod(): int
    {
        return $this->defaultPeriod;
    }
    
    public function shouldRetain(string $metricKey, int $timestamp): bool
    {
        foreach ($this->tiers as $pattern => $period) {
            if (fnmatch($pattern, $metricKey)) {
                return $timestamp >= (time() - $period);
            }
        }
        
        return $timestamp >= (time() - $this->defaultPeriod);
    }
}

use Nexus\Telemetry\Core\SLOWrapper;

class PaymentGateway
{
    public function charge(Payment $payment): void
    {
        $wrapper = SLOWrapper::for(
            $this->telemetry,
            'payment.charge',
            tags: ['gateway' => $payment->gateway]
        );
        
        // Automatically tracks:
        // - slo.payment.charge.success (on success)
        // - slo.payment.charge.failure (on exception)
        // - slo.payment.charge.latency (always)
        // - slo.payment.charge.total (always)
        $wrapper->execute(function() use ($payment) {
            return $this->gateway->processPayment($payment);
        });
    }
}

// app/Providers/MonitoringServiceProvider.php
$this->app->singleton(MetricStorageInterface::class, RedisMetricStorage::class);
$this->app->singleton(TelemetryTrackerInterface::class, TelemetryTracker::class);