Package

Cboxdk System Metrics

Peek into your low level system metrics with PHP

Package

cboxdk/system-metrics

View on GitHub →

Cbox System Metrics

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";

Table of Contents

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, /sys filesystems
    • macOS: Access to sysctl, vm_stat, sw_vers commands

Note: No special permissions or root access required.

Installation

composer require cboxdk/system-metrics

Quick Start

Complete System Overview

use 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";
}

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

Basic Usage

Advanced Features

Architecture

Platform Support

  • Linux - Linux-specific implementation
  • macOS - macOS-specific implementation
  • Comparison - Feature parity table

Reference

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.

Cboxdk System Metrics Related Articles

Health for Laravel: Kubernetes Probes and Prometheus Metrics image

Health for Laravel: Kubernetes Probes and Prometheus Metrics

Read article
APM vs. Logging: Do I Need Both? image

APM vs. Logging: Do I Need Both?

Read article
Announcing Laravel Pulse - A New Performance Monitoring Tool for Laravel Apps image

Announcing Laravel Pulse - A New Performance Monitoring Tool for Laravel Apps

Read article
Track Metrics Effortlessly with Laravel's Context Increment and Decrement Methods image

Track Metrics Effortlessly with Laravel's Context Increment and Decrement Methods

Read article
Query Builder Expression Aliases in Laravel 12.48 image

Query Builder Expression Aliases in Laravel 12.48

Read article
Conditional Collection Skipping with Laravel's skipWhile Method image

Conditional Collection Skipping with Laravel's skipWhile Method

Read article

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm

Pushsilver

Pushsilver is simple invoicing for freelancers and small studios — send polished invoices, automate reminders, and get paid on time without the bloat.

Pushsilver

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $9500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum