PHPackages                             tourze/server-stats-bundle - 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. tourze/server-stats-bundle

ActiveSymfony-bundle[Logging &amp; Monitoring](/categories/logging)

tourze/server-stats-bundle
==========================

功能强大的 Symfony Bundle，用于收集、存储和可视化全面的服务器统计信息和监控数据，包括 CPU、内存、网络流量、磁盘 I/O 等系统指标

1.0.1(7mo ago)00MITPHPCI passing

Since May 20Pushed 6mo ago1 watchersCompare

[ Source](https://github.com/tourze/server-stats-bundle)[ Packagist](https://packagist.org/packages/tourze/server-stats-bundle)[ RSS](/packages/tourze-server-stats-bundle/feed)WikiDiscussions master Synced today

READMEChangelog (3)Dependencies (42)Versions (4)Used By (0)

Server Stats Bundle
===================

[](#server-stats-bundle)

[English](README.md) | [中文](README.zh-CN.md)

\[[![Latest Version](https://camo.githubusercontent.com/811390f223a19063e50886e1597bf8503798cd825751bd1754ebd3021ac0df2c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f746f75727a652f7365727665722d73746174732d62756e646c652e7376673f7374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/811390f223a19063e50886e1597bf8503798cd825751bd1754ebd3021ac0df2c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f746f75727a652f7365727665722d73746174732d62756e646c652e7376673f7374796c653d666c61742d737175617265)\] () [![License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE)[![PHP Version](https://camo.githubusercontent.com/150e1fb3defd53b8f722bfb7cea27d0f7f129d8d8d472e092c6696a326bd69a4/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344382e312d626c75652e7376673f7374796c653d666c61742d737175617265)](https://php.net)\[[![Build Status](https://camo.githubusercontent.com/0346e18af1343d739d0405776c07b83798d5bb0200e3efcfdf657e5e662f6403/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f746f75727a652f7068702d6d6f6e6f7265706f2f63692e796d6c3f7374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/0346e18af1343d739d0405776c07b83798d5bb0200e3efcfdf657e5e662f6403/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f746f75727a652f7068702d6d6f6e6f7265706f2f63692e796d6c3f7374796c653d666c61742d737175617265)\] () \[[![Code Coverage](https://camo.githubusercontent.com/6ce0146325478eb7cebae4cc6139b2af2c161735dd0e3c6ff6802f2c5a708179/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f746f75727a652f7068702d6d6f6e6f7265706f3f7374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/6ce0146325478eb7cebae4cc6139b2af2c161735dd0e3c6ff6802f2c5a708179/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f746f75727a652f7068702d6d6f6e6f7265706f3f7374796c653d666c61742d737175617265)\] ()

A powerful Symfony bundle for collecting, storing, and visualizing comprehensive server statistics and monitoring data.

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

[](#table-of-contents)

- [Features](#features)
- [Installation](#installation)
- [Requirements](#requirements)
- [Quick Start](#quick-start)
- [Configuration](#configuration)
- [API Endpoints](#api-endpoints)
- [Usage Examples](#usage-examples)
- [Advanced Usage](#advanced-usage)
- [License](#license)

Features
--------

[](#features)

- **Complete Server Monitoring**: CPU usage, memory consumption, system load, and process statistics
- **Network Traffic Analysis**: Real-time bandwidth monitoring with RX/TX statistics
- **Storage &amp; Disk I/O**: Comprehensive disk performance metrics including IOPS and wait times
- **TCP/UDP Connection Tracking**: Monitor network connections and protocol statistics
- **Multi-timeframe Charts**: 24-hour and 7-day visualizations with automatic data aggregation
- **EasyAdmin Integration**: Built-in admin interface for data management and visualization
- **Automatic Data Cleanup**: Configurable retention policies with scheduled cleanup
- **Historical Data Aggregation**: Daily and monthly traffic summaries for long-term analysis

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

[](#installation)

```
composer require tourze/server-stats-bundle
```

Requirements
------------

[](#requirements)

- PHP 8.1 or higher
- Symfony 6.4 or higher
- Doctrine ORM 3.0 or higher
- EasyAdmin Bundle 4.0 or higher

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

[](#quick-start)

### 1. Enable the Bundle

[](#1-enable-the-bundle)

Add the bundle to your Symfony application:

```
// config/bundles.php
return [
    // ... other bundles
    ServerStatsBundle\ServerStatsBundle::class => ['all' => true],
];
```

### 2. Create Database Tables

[](#2-create-database-tables)

Run the following commands to create the required database tables:

```
php bin/console doctrine:migrations:migrate
```

### 3. Configure Data Collection

[](#3-configure-data-collection)

The bundle provides several entities for storing server statistics:

- **`MinuteStat`** - Detailed minute-level server statistics including:

    - CPU metrics (user, system, stolen, idle percentages)
    - Memory statistics (total, used, free, available, buffer, cache)
    - System load averages (1min, 5min, 15min)
    - Process counts (running, total, waiting)
    - Network bandwidth (RX/TX)
    - Disk I/O performance metrics
    - TCP/UDP connection statistics
    - Online user tracking
- **`DailyTraffic`** - Daily traffic aggregation by IP and node
- **`MonthlyTraffic`** - Monthly traffic summaries for long-term analysis

### 4. Access the Dashboard

[](#4-access-the-dashboard)

Once configured, you can access the monitoring dashboard through your EasyAdmin interface:

- **Load Monitor**: `/admin/load-monitor/{nodeId}` - CPU, memory, and process monitoring
- **Network Monitor**: `/admin/network-monitor/{nodeId}` - Network traffic analysis with charts

API Endpoints
-------------

[](#api-endpoints)

### Load Conditions

[](#load-conditions)

Get server load conditions:

```
GET /api/load-conditions/{nodeId}

```

Response:

```
{
  "avgCpuUsage": 45.2,
  "avgLoad": 2.1,
  "avgMemUsage": 68.5,
  "avgProcess": 120
}
```

Configuration
-------------

[](#configuration)

The bundle automatically configures itself through dependency injection. No additional configuration is required.

### Data Retention

[](#data-retention)

The bundle includes automatic data cleanup for `MinuteStat` entities:

- **Default retention**: 60 days
- **Cleanup schedule**: Daily at 5:14 AM
- **Environment variable**: `SERVER_NODE_STAT_PERSIST_DAY_NUM` to customize retention period

### Monitoring Dashboard

[](#monitoring-dashboard)

The bundle provides two main dashboard views:

1. **Load Monitor** (`/admin/load-monitor/{nodeId}`):

    - CPU usage charts (user, system, stolen, idle)
    - Memory utilization graphs
    - System load averages
    - Process count monitoring
    - Summary cards with average values
2. **Network Monitor** (`/admin/network-monitor/{nodeId}`):

    - 24-hour bandwidth charts
    - 7-day traffic trends
    - RX/TX data visualization
    - Real-time network statistics

Usage Examples
--------------

[](#usage-examples)

### Using the NodeMonitorService

[](#using-the-nodemonitorservice)

```
use ServerStatsBundle\Service\NodeMonitorService;
use ServerNodeBundle\Entity\Node;

class YourController
{
    public function __construct(
        private NodeMonitorService $nodeMonitorService
    ) {}

    public function getNetworkStats(Node $node): array
    {
        // Returns 24-hour and 7-day network monitoring data
        $data = $this->nodeMonitorService->getNetworkMonitorData($node);

        // Available data includes:
        // - labels24h: hourly labels for 24h chart
        // - rxData24h/txData24h: 24-hour bandwidth data
        // - labels7d: daily labels for 7-day chart
        // - rxData7d/txData7d: 7-day bandwidth data
        return $data;
    }

    public function getLoadStats(Node $node): array
    {
        // Returns comprehensive load monitoring data
        $data = $this->nodeMonitorService->getLoadMonitorData($node);

        // Available data includes:
        // - CPU metrics: cpuUserData, cpuSystemData, cpuIdleData
        // - Load averages: loadOneData, loadFiveData, loadFifteenData
        // - Memory data: memoryTotalData, memoryUsedData, memoryFreeData
        // - Process data: processRunningData, processTotalData
        // - Summary averages: avgCpuUsage, avgLoad, avgMemUsage, avgProcess
        return $data;
    }
}
```

### Working with Repositories

[](#working-with-repositories)

```
use ServerStatsBundle\Repository\MinuteStatRepository;
use ServerStatsBundle\Repository\DailyTrafficRepository;
use ServerStatsBundle\Repository\MonthlyTrafficRepository;
use ServerStatsBundle\Entity\DailyTraffic;
use ServerStatsBundle\Entity\MonthlyTraffic;
use ServerNodeBundle\Entity\Node;

class StatsService
{
    public function __construct(
        private MinuteStatRepository $minuteStatRepository,
        private DailyTrafficRepository $dailyTrafficRepository,
        private MonthlyTrafficRepository $monthlyTrafficRepository
    ) {}

    public function getRecentStats(Node $node): array
    {
        // Get recent minute-level statistics
        $qb = $this->minuteStatRepository->createQueryBuilder('s')
            ->where('s.node = :node')
            ->andWhere('s.datetime >= :startTime')
            ->setParameter('node', $node)
            ->setParameter('startTime', new \DateTime('-1 hour'))
            ->orderBy('s.datetime', 'DESC')
            ->setMaxResults(60);

        return $qb->getQuery()->getResult();
    }

    public function getDailyTraffic(Node $node, \DateTimeInterface $date): ?DailyTraffic
    {
        return $this->dailyTrafficRepository->findOneBy([
            'node' => $node,
            'date' => $date
        ]);
    }

    public function getMonthlyTraffic(Node $node, \DateTimeInterface $month): ?MonthlyTraffic
    {
        return $this->monthlyTrafficRepository->findOneBy([
            'node' => $node,
            'month' => $month
        ]);
    }
}
```

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

[](#advanced-usage)

### Custom Data Collection

[](#custom-data-collection)

You can extend the bundle's data collection capabilities by creating custom collectors:

```
use ServerStatsBundle\Entity\MinuteStat;
use ServerNodeBundle\Entity\Node;
use Doctrine\ORM\EntityManagerInterface;

class CustomStatsCollector
{
    public function __construct(
        private EntityManagerInterface $entityManager
    ) {}

    public function collectCustomStats(Node $node): void
    {
        $stat = new MinuteStat();
        $stat->setNode($node);
        $stat->setDatetime(new \DateTime());

        // Set custom metrics
        $stat->setCpuUserPercent($this->getCpuUsage());
        $stat->setMemoryUsed($this->getMemoryUsage());
        // ... other metrics

        $this->entityManager->persist($stat);
        $this->entityManager->flush();
    }

    private function getCpuUsage(): float
    {
        // Your custom CPU collection logic
        return 0.0;
    }

    private function getMemoryUsage(): int
    {
        // Your custom memory collection logic
        return 0;
    }
}
```

### Data Aggregation

[](#data-aggregation)

For performance optimization, you can create custom data aggregators:

```
use ServerStatsBundle\Repository\MinuteStatRepository;
use ServerStatsBundle\Entity\DailyTraffic;

class DataAggregator
{
    public function __construct(
        private MinuteStatRepository $minuteStatRepository,
        private EntityManagerInterface $entityManager
    ) {}

    public function aggregateDailyData(Node $node, \DateTimeInterface $date): void
    {
        $startDate = (clone $date)->setTime(0, 0, 0);
        $endDate = (clone $date)->setTime(23, 59, 59);

        $qb = $this->minuteStatRepository->createQueryBuilder('s')
            ->select('SUM(s.rxBandwidth) as totalRx, SUM(s.txBandwidth) as totalTx')
            ->where('s.node = :node')
            ->andWhere('s.datetime BETWEEN :start AND :end')
            ->setParameter('node', $node)
            ->setParameter('start', $startDate)
            ->setParameter('end', $endDate);

        $result = $qb->getQuery()->getSingleResult();

        // Create daily aggregation
        $dailyTraffic = new DailyTraffic();
        $dailyTraffic->setNode($node);
        $dailyTraffic->setDate($date);
        $dailyTraffic->setRx($result['totalRx']);
        $dailyTraffic->setTx($result['totalTx']);

        $this->entityManager->persist($dailyTraffic);
        $this->entityManager->flush();
    }
}
```

### Custom Monitoring Dashboard

[](#custom-monitoring-dashboard)

Create custom dashboard controllers for specialized monitoring views:

```
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use ServerStatsBundle\Service\NodeMonitorService;
use ServerNodeBundle\Entity\Node;

#[Route('/admin/custom-monitor')]
class CustomMonitorController extends AbstractController
{
    #[Route('/{id}/performance', name: 'admin_custom_performance_monitor')]
    public function performanceMonitor(
        Node $node,
        NodeMonitorService $nodeMonitorService
    ): Response {
        $data = $nodeMonitorService->getLoadMonitorData($node);

        // Add custom calculations
        $data['performanceScore'] = $this->calculatePerformanceScore($data);

        return $this->render('admin/custom_performance_monitor.html.twig', [
            'node' => $node,
            'data' => $data,
        ]);
    }

    private function calculatePerformanceScore(array $data): float
    {
        // Custom performance scoring logic
        $cpuScore = 100 - $data['avgCpuUsage'];
        $memScore = 100 - $data['avgMemUsage'];
        $loadScore = max(0, 100 - ($data['avgLoad'] * 50));

        return ($cpuScore + $memScore + $loadScore) / 3;
    }
}
```

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

[](#contributing)

Contributions are welcome! Please follow these guidelines:

1. **Fork the repository** and create your feature branch from `master`
2. **Write tests** for your changes using PHPUnit
3. **Follow code standards** - use PHPStan and coding style guidelines
4. **Update documentation** if you're adding new features
5. **Submit a pull request** with a clear description of your changes

### Running Tests

[](#running-tests)

```
# Run all tests
./vendor/bin/phpunit packages/server-stats-bundle/tests

# Run PHPStan analysis
php -d memory_limit=2G ./vendor/bin/phpstan analyse packages/server-stats-bundle

# Run package checks
bin/console app:check-packages server-stats-bundle -o -f
```

### Code Quality

[](#code-quality)

Please ensure your code passes all quality checks:

- All tests must pass
- PHPStan analysis must be clean (level 9)
- Follow PSR-12 coding standards
- Add proper type declarations

License
-------

[](#license)

This bundle is released under the MIT License. See the bundled LICENSE file for details.

###  Health Score

29

—

LowBetter than 57% of packages

Maintenance65

Regular maintenance activity

Popularity0

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity39

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

Every ~89 days

Total

3

Last Release

234d ago

Major Versions

0.0.1 → 1.0.02025-11-05

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/13899502?v=4)[tourze](/maintainers/tourze)[@tourze](https://github.com/tourze)

---

Top Contributors

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

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tourze-server-stats-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/tourze-server-stats-bundle/health.svg)](https://phpackages.com/packages/tourze-server-stats-bundle)
```

###  Alternatives

[oro/platform

Business Application Platform (BAP)

645143.5k115](/packages/oro-platform)[easycorp/easyadmin-bundle

Admin generator for Symfony applications

4.3k17.9M388](/packages/easycorp-easyadmin-bundle)[open-dxp/opendxp

Content &amp; Product Management Framework (CMS/PIM)

9421.6k61](/packages/open-dxp-opendxp)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.4M204](/packages/sulu-sulu)[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.5k5.9M738](/packages/sylius-sylius)[contao/core-bundle

Contao Open Source CMS

1231.6M2.8k](/packages/contao-core-bundle)

PHPackages © 2026

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