PHPackages                             azaharizaman/nexus-telemetry - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Logging &amp; Monitoring](/categories/logging)
4. /
5. azaharizaman/nexus-telemetry

ActiveLibrary[Logging &amp; Monitoring](/categories/logging)

azaharizaman/nexus-telemetry
============================

Framework-agnostic monitoring, telemetry tracking, health checks, and alert management package for the Nexus ERP system

v0.1.0-alpha1(1mo ago)003MITPHPPHP ^8.3

Since May 5Pushed 1mo agoCompare

[ Source](https://github.com/azaharizaman/nexus-telemetry)[ Packagist](https://packagist.org/packages/azaharizaman/nexus-telemetry)[ RSS](/packages/azaharizaman-nexus-telemetry/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependencies (2)Versions (2)Used By (3)

Nexus\\Telemetry
================

[](#nexustelemetry)

[![Tests](https://camo.githubusercontent.com/08c71b091c76e6a4abaedda93d5d5903ac5c9254d834c51546195625d0cfc916/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f74657374732d31383825323070617373696e672d73756363657373)](./TEST_SUITE_SUMMARY.md)[![PHP](https://camo.githubusercontent.com/ef0054230522e542bc1f908ac005c6c75888dea255bac910f9015e12095e31d7/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e332d626c7565)](https://php.net)[![License](https://camo.githubusercontent.com/b8cadaa967891081f8f165695470689986c028821dd8a040132f6e661795dc0d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c7565)](./LICENSE)[![Documentation](https://camo.githubusercontent.com/0f72dc624aeaea5d8ef0243d33d7249f616ca8cb72bef95ee2e7f31f5b58a019/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f646f63756d656e746174696f6e2d313030253235253230636f6d706c69616e742d627269676874677265656e)](./DOCUMENTATION_COMPLIANCE_SUMMARY.md)

> **Comprehensive observability package for the Nexus ERP monorepo**
> Production-grade monitoring with metrics, health checks, alerting, and automated retention.

---

📋 Table of Contents
-------------------

[](#-table-of-contents)

- [Overview](#overview)
- [Features](#features)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Core Components](#core-components)
- [Advanced Usage](#advanced-usage)
- [Available Interfaces](#available-interfaces)
- [Testing](#testing)
- [Documentation](#documentation)
- [Architecture](#architecture)
- [Contributing](#contributing)

---

Overview
--------

[](#overview)

The **Nexus\\Telemetry** package provides a complete observability solution for the Nexus ERP system. Built with framework-agnostic design principles, it offers:

- **Telemetry Tracking** - Record metrics with cardinality protection and multi-tenancy support
- **Health Checks** - Monitor system components with built-in checks and custom implementations
- **Alerting** - Evaluate and dispatch alerts with deduplication and severity mapping
- **SLO Tracking** - Automatic Service Level Objective instrumentation
- **Metric Retention** - Automated cleanup with configurable policies
- **Easy Integration** - Trait-based pattern for seamless adoption

### Design Philosophy

[](#design-philosophy)

1. **Framework Agnostic** - Pure PHP with PSR interfaces
2. **Test-Driven** - 188 tests with 476 assertions (100% passing)
3. **Zero Infrastructure Coupling** - Implementations injected via interfaces
4. **Production Ready** - Battle-tested patterns with comprehensive error handling

---

Features
--------

[](#features)

### ✅ Metric Tracking

[](#-metric-tracking)

- **Multiple metric types**: Counter, Gauge, Timer, Histogram
- **Cardinality protection**: Prevent tag explosion
- **Sampling support**: Reduce storage costs for high-volume metrics
- **Multi-tenancy**: Automatic tenant context tagging
- **Trace context**: OpenTelemetry-compatible trace/span IDs

### ✅ Health Checks

[](#-health-checks)

- **Built-in checks**: Database, Cache, Disk Space, Memory
- **Template method pattern**: Easy custom check creation
- **Priority-based execution**: Critical checks first
- **Timeout handling**: Graceful degradation
- **Result caching**: Configurable TTL per check

### ✅ Alerting

[](#-alerting)

- **Exception-to-severity mapping**: Automatic alert classification
- **Fingerprint deduplication**: Prevent alert storms
- **Time-window deduplication**: Configurable silence periods
- **Metadata enrichment**: Stack traces, exception details
- **Channel dispatching**: Email, SMS, Slack, PagerDuty

### ✅ Utilities

[](#-utilities)

- **SLO Wrapper**: Automatic success/failure/latency tracking
- **Monitoring Trait**: 6 convenience methods for quick integration
- **Custom Exceptions**: Domain-specific error handling
- **Retention Service**: Automated metric cleanup with policies

---

Available Interfaces
--------------------

[](#available-interfaces)

The package provides 15 interfaces for complete flexibility and framework agnosticism:

### Core Tracking &amp; Storage

[](#core-tracking--storage)

- **`TelemetryTrackerInterface`** - Record metrics (counter, gauge, timing, histogram)
- **`MetricStorageInterface`** - Store and query metrics with aggregation
- **`MetricRetentionInterface`** - Define retention policies for metric cleanup

### Health Monitoring

[](#health-monitoring)

- **`HealthCheckerInterface`** - Register and execute health checks
- **`HealthCheckInterface`** - Implement custom health checks
- **`ScheduledHealthCheckInterface`** - Health checks with cron-like scheduling

### Alerting

[](#alerting)

- **`AlertGatewayInterface`** - Evaluate exceptions and dispatch alerts
- **`AlertDispatcherInterface`** - Send alerts to notification channels

### Cardinality Protection

[](#cardinality-protection)

- **`CardinalityGuardInterface`** - Prevent metric tag explosion
- **`CardinalityStorageInterface`** - Track unique tag values (HyperLogLog recommended)

### Configuration &amp; Context

[](#configuration--context)

- **`SLOConfigurationInterface`** - Define Service Level Objectives
- **`SamplingStrategyInterface`** - Implement metric sampling (probabilistic, deterministic, adaptive)
- **`CacheRepositoryInterface`** - Cache health check results
- **`TenantContextInterface`** - Multi-tenancy support (optional, from Nexus\\Tenant)

### Additional Utilities

[](#additional-utilities)

- **`MonitoringAwareTrait`** - Convenience methods for quick integration (6 helper methods)

---

Installation
------------

[](#installation)

### Requirements

[](#requirements)

- PHP 8.3 or higher
- Composer

### Install via Composer

[](#install-via-composer)

```
composer require azaharizaman/nexus-telemetry:"*@dev"
```

*Note: Package is currently in development. Use `@dev` stability flag.*

---

Quick Start
-----------

[](#quick-start)

### 1. Basic Metric Tracking

[](#1-basic-metric-tracking)

```
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']);
```

### 2. Health Checks

[](#2-health-checks)

```
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
```

### 3. Easy Integration with Trait

[](#3-easy-integration-with-trait)

```
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);
    }
}
```

### 4. Automated Metric Retention

[](#4-automated-metric-retention)

```
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();
```

---

Core Components
---------------

[](#core-components)

### TelemetryTracker

[](#telemetrytracker)

Records metrics with protection and enrichment.

**Key Features:**

- Cardinality limit enforcement
- Automatic tenant tagging
- OpenTelemetry trace context
- Sampling for high-volume metrics

**Methods:**

```
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
```

### HealthCheckRunner

[](#healthcheckrunner)

Orchestrates health checks with intelligent execution.

**Key Features:**

- Priority-based ordering (critical first)
- Timeout protection with circuit breaking
- Result caching with configurable TTL
- Scheduled vs on-demand execution

**Methods:**

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

### AlertEvaluator

[](#alertevaluator)

Processes exceptions into alerts with deduplication.

**Key Features:**

- Automatic severity mapping
- Fingerprint-based deduplication
- Time-window silence periods
- Metadata enrichment (stack traces)

**Methods:**

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

### MetricRetentionService

[](#metricretentionservice)

Manages metric lifecycle and cleanup.

**Key Features:**

- Policy-driven retention (time-based, tiered)
- Batch pruning with size limits
- Threshold-based automatic cleanup
- Comprehensive statistics

**Methods:**

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

---

Advanced Usage
--------------

[](#advanced-usage)

### Custom Health Check

[](#custom-health-check)

```
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()
        };
    }
}
```

### Custom Retention Policy

[](#custom-retention-policy)

```
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);
    }
}
```

### SLO Tracking Pattern

[](#slo-tracking-pattern)

```
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);
        });
    }
}
```

---

Testing
-------

[](#testing)

### Run All Tests

[](#run-all-tests)

```
cd packages/Monitoring
vendor/bin/phpunit
```

### Run Specific Test Suite

[](#run-specific-test-suite)

```
# Services only
vendor/bin/phpunit tests/Unit/Services/

# Health checks only
vendor/bin/phpunit tests/Unit/Core/

# With coverage (requires xdebug)
vendor/bin/phpunit --coverage-html coverage-report
```

### Test Statistics

[](#test-statistics)

- **Total Tests:** 188
- **Total Assertions:** 476
- **Coverage:** Comprehensive (all production code tested)
- **Runtime:** ~2 seconds
- **Status:** ✅ All passing

See [TEST\_SUITE\_SUMMARY.md](./TEST_SUITE_SUMMARY.md) for detailed breakdown.

---

Architecture
------------

[](#architecture)

### Package Structure

[](#package-structure)

```
packages/Monitoring/
├── src/
│   ├── Contracts/           # 15 interfaces (framework-agnostic)
│   ├── Services/            # 4 core services
│   ├── HealthChecks/        # Built-in health checks
│   ├── Core/                # Utilities (SLOWrapper, Policies)
│   ├── ValueObjects/        # Immutable data objects
│   ├── Exceptions/          # 5 custom exceptions
│   └── Traits/              # MonitoringAwareTrait
├── tests/
│   └── Unit/                # 188 comprehensive tests
├── composer.json
├── phpunit.xml
└── README.md

```

### Key Design Patterns

[](#key-design-patterns)

1. **Dependency Injection** - All dependencies via constructor
2. **Interface Segregation** - Small, focused contracts
3. **Template Method** - AbstractHealthCheck pattern
4. **Strategy Pattern** - Pluggable sampling, retention policies
5. **Decorator Pattern** - SLOWrapper for cross-cutting concerns
6. **Trait Composition** - MonitoringAwareTrait for easy integration

### Framework Integration

[](#framework-integration)

The package is **framework-agnostic** by design. Integration examples:

**Laravel:**

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

**Symfony:**

```
# config/services.yaml
services:
  Nexus\Telemetry\Contracts\MetricStorageInterface:
    class: App\Infrastructure\RedisMetricStorage

  Nexus\Telemetry\Services\TelemetryTracker:
    autowire: true
```

---

Contributing
------------

[](#contributing)

### Development Setup

[](#development-setup)

```
# Clone monorepo
git clone https://github.com/azaharizaman/atomy.git
cd atomy/packages/Monitoring

# Install dependencies
composer install

# Run tests
vendor/bin/phpunit

# Run static analysis (if configured)
vendor/bin/phpstan analyse
```

### Coding Standards

[](#coding-standards)

- **PHP Version:** 8.3+
- **Style Guide:** PSR-12
- **Type Safety:** Strict types enabled (`declare(strict_types=1)`)
- **Modern PHP:** Property promotion, readonly properties, enums
- **Testing:** TDD approach with comprehensive coverage

### Pull Request Process

[](#pull-request-process)

1. Create feature branch from `main`
2. Write tests first (TDD)
3. Implement feature with strict types
4. Ensure all tests pass
5. Update documentation
6. Submit PR with clear description

---

Documentation
-------------

[](#documentation)

### Package Documentation

[](#package-documentation)

- **[Getting Started](./docs/getting-started.md)** - Quick start guide with installation and basic examples
- **[API Reference](./docs/api-reference.md)** - Complete API documentation for all 15 interfaces
- **[Integration Guide](./docs/integration-guide.md)** - Framework integration (Laravel, Symfony, vanilla PHP)
- **[Examples](./docs/examples/)** - Working code examples
    - [Basic Usage](./docs/examples/basic-usage.php) - Metric tracking, health checks, querying
    - [Advanced Usage](./docs/examples/advanced-usage.php) - Multi-tenancy, cardinality protection, SLO tracking

### Implementation Documentation

[](#implementation-documentation)

- **[Implementation Summary](./IMPLEMENTATION_SUMMARY.md)** - Development phases, metrics, design decisions
- **[Requirements](./REQUIREMENTS.md)** - Complete requirements traceability (52 requirements)
- **[Test Suite Summary](./TEST_SUITE_SUMMARY.md)** - Test coverage and results
- **[Valuation Matrix](./VALUATION_MATRIX.md)** - Package valuation and ROI analysis

### Architecture Documentation

[](#architecture-documentation)

- **[Architecture](../../ARCHITECTURE.md)** - Monorepo design principles
- **[Metric Retention Guide](./METRIC_RETENTION_IMPLEMENTATION.md)** - Retention policies deep dive

---

Testing
-------

[](#testing-1)

The package has comprehensive test coverage with **188 tests** and **476 assertions** (100% passing).

### Test Statistics

[](#test-statistics-1)

- **Total Tests:** 188
- **Assertions:** 476
- **Success Rate:** 100%
- **Execution Time:** ~2 seconds
- **PHPUnit Version:** 11.0
- **Coverage:** All public interfaces, services, value objects, enums, exceptions

### Test Breakdown

[](#test-breakdown)

- **TelemetryTracker:** 17 tests (all metric types, cardinality protection, multi-tenancy)
- **HealthCheckRunner:** 14 tests (priority execution, timeout handling, caching)
- **AlertEvaluator:** 15 tests (severity mapping, deduplication, dispatching)
- **MetricRetentionService:** 12 tests (pruning, stats, policy enforcement)
- **Built-in Health Checks:** 130+ tests (Database, Cache, DiskSpace, Memory)

### Running Tests

[](#running-tests)

```
# Run all tests
composer test

# Run with coverage report
composer test:coverage

# Run specific test suite
vendor/bin/phpunit tests/Unit/Services/TelemetryTrackerTest.php
```

---

Documentation
-------------

[](#documentation-1)

- **[Architecture](../../ARCHITECTURE.md)** - Monorepo design principles
- **[Implementation Summary](../../docs/MONITORING_IMPLEMENTATION_SUMMARY.md)** - Detailed feature breakdown
- **[Test Suite Summary](./TEST_SUITE_SUMMARY.md)** - Test coverage details
- **[Metric Retention Guide](./METRIC_RETENTION_IMPLEMENTATION.md)** - Retention policies

---

License
-------

[](#license)

MIT License - see [LICENSE](./LICENSE) file for details.

---

Roadmap
-------

[](#roadmap)

### Completed ✅

[](#completed-)

- TelemetryTracker with cardinality protection
- HealthCheckRunner with priority-based execution
- AlertEvaluator with deduplication
- Built-in health checks (Database, Cache, DiskSpace, Memory)
- SLOWrapper utility
- MonitoringAwareTrait
- Custom exceptions with factory methods
- MetricRetentionService with time-based policies

### Planned 🎯

[](#planned-)

- Additional health checks (Queue, Storage, External APIs)
- Metric aggregation service (hourly → daily → monthly)
- Dashboard data export (Grafana, Prometheus format)
- Anomaly detection with ML
- Distributed tracing integration
- Custom alert channels (Teams, Discord, Telegram)

---

Support
-------

[](#support)

For issues, questions, or contributions:

- **Issues:** [GitHub Issues](https://github.com/azaharizaman/atomy/issues)
- **Discussions:** [GitHub Discussions](https://github.com/azaharizaman/atomy/discussions)
- **Documentation:** [docs/](../../docs/)

---

**Built with ❤️ for the Nexus ERP ecosystem**

###  Health Score

35

—

LowBetter than 77% of packages

Maintenance93

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity34

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

36d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/117408?v=4)[Azahari Zaman](/maintainers/azaharizaman)[@azaharizaman](https://github.com/azaharizaman)

---

Top Contributors

[![azaharizaman](https://avatars.githubusercontent.com/u/117408?v=4)](https://github.com/azaharizaman "azaharizaman (4 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/azaharizaman-nexus-telemetry/health.svg)

```
[![Health](https://phpackages.com/badges/azaharizaman-nexus-telemetry/health.svg)](https://phpackages.com/packages/azaharizaman-nexus-telemetry)
```

###  Alternatives

[sentry/sentry

PHP SDK for Sentry (http://sentry.io)

1.9k240.0M312](/packages/sentry-sentry)[matomo/matomo

Matomo is the leading Free/Libre open analytics platform

21.6k38.2k](/packages/matomo-matomo)[illuminate/log

The Illuminate Log package.

6225.0M597](/packages/illuminate-log)[tempest/framework

The PHP framework that gets out of your way.

2.2k31.1k11](/packages/tempest-framework)[api-platform/metadata

API Resource-oriented metadata attributes and factories

244.5M180](/packages/api-platform-metadata)[pagemachine/typo3-formlog

Form log for TYPO3

23233.9k7](/packages/pagemachine-typo3-formlog)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
