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 Cbox\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";- Features
- Requirements
- Installation
- Quick Start
- Documentation
- Testing
- Changelog
- Contributing
- Security
- Credits
- License
✨ 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
- 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.
composer require cboxdk/system-metricsuse Cbox\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 (cgroup-aware — shows container limit when containerized)
if ($overview->limits !== null) {
echo "Memory: " . round($overview->limits->memoryUtilization(), 1) . "%\n";
echo "Containerized: " . ($overview->limits->isContainerized() ? 'yes' : 'no') . "\n";
}
// Load Average
echo "Load Average (1 min): {$overview->loadAverage?->oneMinute}\n";
// Uptime
echo "Uptime: {$overview->uptime?->humanReadable()}\n";
}// 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 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";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()));Comprehensive documentation is available in the docs/ directory:
- Introduction - Overview and key features
- Installation - Installation and setup
- Quick Start - 30-second working example
- 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
- 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
- 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
- Linux - Linux-specific implementation
- macOS - macOS-specific implementation
- Comparison - Feature parity table
- API Reference - Complete method documentation
- Testing Guide - Running tests and coverage
- Roadmap - Planned features
# Run tests
composer test
# With coverage
composer test-coverage
# Static analysis
composer analyse
# Code style
composer formatSee Testing Guide for details.
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.