gophpeek / system-metrics
Peek into your low level system metrics with PHP
Fund package maintenance!
gophpeek
Installs: 103
Dependents: 1
Suggesters: 0
Security: 0
Stars: 0
Watchers: 0
Forks: 0
Open Issues: 0
pkg:composer/gophpeek/system-metrics
Requires
- php: ^8.3
Requires (Dev)
- laravel/pint: ^1.0
- pestphp/pest: ^4.1
- phpstan/phpstan: ^2.0
This package is auto-updated.
Last update: 2025-11-18 22:44:31 UTC
README
Get real-time system metrics from Linux and macOS in pure PHP. No extensions, no dependencies, just clean type-safe access to CPU, memory, storage, network, and container metrics.
use PHPeek\SystemMetrics\SystemMetrics; $overview = SystemMetrics::overview()->getValue(); echo "OS: {$overview->environment->os->name}\n"; echo "CPU Cores: {$overview->cpu->coreCount()}\n"; echo "Memory: " . round($overview->memory->usedPercentage(), 1) . "%\n";
Table of Contents
- Features
- Requirements
- Installation
- Quick Start
- Documentation
- Testing
- Changelog
- Contributing
- Security
- Credits
- License
Features
✨ Pure PHP Implementation
- No PHP extensions required
- No Composer dependencies
- Works out of the box on any Linux or macOS system
🔒 Type-Safe with Modern PHP
- Built for PHP 8.3+ with readonly classes
- Strict types everywhere (
declare(strict_types=1)) - Full PHPStan Level 9 compliance
🎯 Explicit Error Handling
- Result pattern instead of exceptions
- Explicit success/failure handling at compile time
- No uncaught exceptions in production
📊 Comprehensive Metrics
- Environment detection (OS, kernel, architecture, virtualization, containers)
- CPU metrics (raw time counters, per-core data, usage calculations)
- Memory metrics (physical RAM, swap, buffers, cache)
- Load average with per-core normalization
- System uptime tracking
- Storage metrics (filesystem usage, disk I/O)
- Network metrics (interface stats, connections)
- Container metrics (cgroup v1/v2, Docker, Kubernetes)
- Process metrics (individual and group monitoring)
- Unified limits API (environment-aware resource limits)
🏗️ Production-Ready
- 89.9% test coverage
- PSR-12 code style via Laravel Pint
- Graceful degradation when APIs unavailable
- Performance optimized with static data caching
Requirements
- PHP 8.3 or higher (uses readonly classes)
- Linux or macOS (Windows not supported)
- Standard system access:
- Linux: Read access to
/proc,/sysfilesystems - macOS: Access to
sysctl,vm_stat,sw_verscommands
- Linux: Read access to
Note: No special permissions or root access required.
Installation
composer require gophpeek/system-metrics
Quick Start
Complete System Overview
use PHPeek\SystemMetrics\SystemMetrics; $result = SystemMetrics::overview(); if ($result->isSuccess()) { $overview = $result->getValue(); // Environment echo "OS: {$overview->environment->os->name} {$overview->environment->os->version}\n"; echo "Architecture: {$overview->environment->architecture->kind->value}\n"; // CPU echo "CPU Cores: {$overview->cpu->coreCount()}\n"; // Memory $usedGB = round($overview->memory->usedBytes / 1024**3, 2); echo "Memory Used: {$usedGB} GB\n"; echo "Memory Usage: " . round($overview->memory->usedPercentage(), 1) . "%\n"; // Load Average echo "Load Average (1 min): {$overview->loadAverage->oneMinute}\n"; }
Individual Metrics
// Environment detection $env = SystemMetrics::environment()->getValue(); echo "OS: {$env->os->family->value}\n"; // CPU metrics $cpu = SystemMetrics::cpu()->getValue(); echo "CPU Cores: {$cpu->coreCount()}\n"; // Memory metrics $mem = SystemMetrics::memory()->getValue(); echo "Memory: " . round($mem->usedPercentage(), 1) . "%\n"; // Load average $load = SystemMetrics::loadAverage()->getValue(); echo "Load (1 min): {$load->oneMinute}\n"; // Storage metrics $storage = SystemMetrics::storage()->getValue(); echo "Storage: " . round($storage->usedPercentage(), 1) . "%\n"; // Network metrics $network = SystemMetrics::network()->getValue(); echo "Interfaces: " . count($network->interfaces) . "\n"; // Container metrics (cgroups) $container = SystemMetrics::container()->getValue(); if ($container->hasCpuLimit()) { echo "Container CPU limit: {$container->cpuQuota} cores\n"; } // Unified limits (environment-aware) $limits = SystemMetrics::limits()->getValue(); echo "Available CPU: {$limits->availableCpuCores()} cores\n"; echo "Available Memory: " . round($limits->availableMemoryBytes() / 1024**3, 2) . " GB\n"; // Process monitoring $process = ProcessMetrics::snapshot(getmypid())->getValue(); echo "Process Memory: " . round($process->resources->memoryRssBytes / 1024**2, 2) . " MB\n";
CPU Usage Percentage
CPU metrics return raw time counters. To calculate usage percentage:
// Convenience method (blocks for 1 second) $delta = SystemMetrics::cpuUsage(1.0)->getValue(); echo "CPU Usage: " . round($delta->usagePercentage(), 1) . "%\n"; // Or manually with two snapshots $snap1 = SystemMetrics::cpu()->getValue(); sleep(2); $snap2 = SystemMetrics::cpu()->getValue(); $delta = CpuSnapshot::calculateDelta($snap1, $snap2); echo "CPU Usage: " . round($delta->usagePercentage(), 1) . "%\n";
Error Handling
All methods return Result<T> for explicit error handling:
$result = SystemMetrics::memory(); if ($result->isSuccess()) { $memory = $result->getValue(); echo "Memory: " . round($memory->usedPercentage(), 1) . "%\n"; } else { echo "Error: " . $result->getError()->getMessage() . "\n"; } // Or use functional style SystemMetrics::cpu() ->onSuccess(fn($cpu) => echo "CPU: {$cpu->coreCount()} cores\n") ->onFailure(fn($err) => error_log($err->getMessage()));
Documentation
Comprehensive documentation is available in the docs/ directory:
Getting Started
- Introduction - Overview and key features
- Installation - Installation and setup
- Quick Start - 30-second working example
Basic Usage
- Environment Detection - OS, kernel, architecture, containers
- CPU Metrics - CPU time counters and core data
- Memory Metrics - Physical RAM and swap
- Load Average - System load metrics
- System Uptime - Boot time tracking
- Storage Metrics - Filesystem and disk I/O
- Network Metrics - Interface statistics
- System Overview - Complete snapshot
Advanced Features
- Container Metrics - Cgroup v1/v2, Docker, Kubernetes
- Process Metrics - Process monitoring and tracking
- Unified Limits - Environment-aware resource limits
- CPU Usage Calculation - Delta between snapshots
- Error Handling - Result pattern deep dive
- Custom Implementations - Extend with custom sources
Architecture
- Design Principles - Architectural philosophy
- Result Pattern - Error handling approach
- Composite Sources - Fallback logic
- Immutable DTOs - Data structures
- Action Pattern - Use case encapsulation
- Performance Caching - Optimization strategies
Platform Support
- Linux - Linux-specific implementation
- macOS - macOS-specific implementation
- Comparison - Feature parity table
Reference
- API Reference - Complete method documentation
- Testing Guide - Running tests and coverage
- Roadmap - Planned features
Testing
# Run tests composer test # With coverage composer test-coverage # Static analysis composer analyse # Code style composer format
See Testing Guide for details.
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security
Please review our security policy on how to report security vulnerabilities.
Credits
License
The MIT License (MIT). Please see License File for more information.