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
Metrics: Simple, Elegant Metric Tracking for Laravel image

Metrics: Simple, Elegant Metric Tracking for Laravel

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
Laravel Easy Metrics image

Laravel Easy Metrics

Read article
Monolithic Application Performance Monitoring with Scout image

Monolithic Application Performance Monitoring with Scout

Read article
Worker Metrics on the WorkerStopping Event in Laravel 13.18 image

Worker Metrics on the WorkerStopping Event in Laravel 13.18

Read article

PhpStorm

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

PhpStorm

Let your users buy domains without leaving your app

If your Laravel app gives users a site, a storefront, or a workspace, they’ll eventually want their own domain. The name.com API lets them search, register, and connect one without leaving your product. It’s a clean REST API, so Laravel’s HTTP client is all you need.

Let your users buy domains without leaving your app

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

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum

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