2024-04-14 17:58:26 +02:00
# @push.rocks/smartmetrics
2026-02-19 09:16:43 +00:00
**Powerful system metrics collection for Node.js applications with Prometheus integration** 🚀
## Issue Reporting and Security
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/ ](https://community.foss.global/ ). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/ ](https://code.foss.global/ ) account to submit Pull Requests directly.
2024-04-14 17:58:26 +02:00
2025-06-09 12:34:06 +00:00
## What is SmartMetrics?
2021-08-12 23:19:39 +02:00
2025-06-09 12:34:06 +00:00
SmartMetrics is a comprehensive metrics collection library that monitors your Node.js application's resource usage in real-time. It tracks CPU usage, memory consumption, and system metrics across your main process and all child processes, providing insights through both JSON and Prometheus formats.
2021-08-12 23:19:39 +02:00
2025-06-09 12:34:06 +00:00
## Key Features
2024-04-14 17:58:26 +02:00
2026-02-19 09:16:43 +00:00
- 📊 **Real-time Metrics Collection ** – Monitor CPU and memory usage across all processes
- 🔄 **Automatic Child Process Tracking ** – Aggregates metrics from main and child processes via `pidtree` + `pidusage`
- 🐳 **Docker-Aware ** – Detects container memory limits from cgroup automatically
- 📈 **Prometheus Integration ** – Built-in HTTP endpoint for Prometheus scraping with `prom-client`
- 🔧 **Flexible Output Formats ** – Get metrics as JSON objects or Prometheus text exposition format
- 📝 **Automatic Heartbeat Logging ** – Optional periodic metrics logging via `@push.rocks/smartlog`
- 🚀 **Zero Configuration ** – Works out of the box with sensible defaults
2024-04-14 17:58:26 +02:00
2025-06-09 12:34:06 +00:00
## Installation
2024-04-14 17:58:26 +02:00
2025-06-09 12:34:06 +00:00
```bash
2026-02-19 09:16:43 +00:00
pnpm install @push .rocks/smartmetrics
# or
2025-06-09 12:34:06 +00:00
npm install @push .rocks/smartmetrics
```
2024-04-14 17:58:26 +02:00
2025-06-09 12:34:06 +00:00
## Quick Start
2024-04-14 17:58:26 +02:00
```typescript
import { SmartMetrics } from '@push .rocks/smartmetrics';
import { Smartlog } from '@push .rocks/smartlog';
2025-06-09 12:34:06 +00:00
// Create a logger instance
2024-04-14 17:58:26 +02:00
const logger = new Smartlog({
2026-02-19 09:16:43 +00:00
logContext: null,
minimumLogLevel: 'info',
2024-04-14 17:58:26 +02:00
});
2026-02-19 09:16:43 +00:00
logger.enableConsole();
2024-04-14 17:58:26 +02:00
2025-06-09 12:34:06 +00:00
// Initialize SmartMetrics
const metrics = new SmartMetrics(logger, 'my-service');
// Get metrics on-demand
const currentMetrics = await metrics.getMetrics();
console.log(`CPU Usage: ${currentMetrics.cpuUsageText}` );
console.log(`Memory: ${currentMetrics.memoryUsageText}` );
// Enable automatic heartbeat logging (every 20 seconds)
metrics.start();
// Enable Prometheus endpoint
2026-02-19 09:16:43 +00:00
metrics.enablePrometheusEndpoint(9090);
// Metrics now available at http://localhost:9090/metrics
2025-06-09 12:34:06 +00:00
// Clean shutdown
metrics.stop();
2024-04-14 17:58:26 +02:00
```
2025-06-09 12:34:06 +00:00
## Core Concepts
### Process Aggregation
2026-02-19 09:16:43 +00:00
SmartMetrics doesn't just monitor your main process – it automatically discovers and aggregates metrics from all child processes spawned by your application using `pidtree` . This gives you a complete picture of your application's resource footprint, not just the parent process.
2025-06-09 12:34:06 +00:00
### Memory Limit Detection
2026-02-19 09:16:43 +00:00
The library automatically detects available memory whether running on bare metal, in Docker containers, or with Node.js heap restrictions. It picks the most restrictive of:
1. **System total memory ** (`os.totalmem()` )
2026-02-19 09:46:46 +00:00
2. **Docker cgroup limit ** – supports both cgroup v2 (`/sys/fs/cgroup/memory.max` ) and cgroup v1 (`/sys/fs/cgroup/memory/memory.limit_in_bytes` )
2026-02-19 09:16:43 +00:00
3. **V8 heap size limit ** (`v8.getHeapStatistics().heap_size_limit` )
This ensures accurate percentage calculations regardless of environment.
2024-04-14 17:58:26 +02:00
2025-06-09 12:34:06 +00:00
### Dual Output Formats
2026-02-19 09:16:43 +00:00
- **JSON Format** (`getMetrics()` ) – Ideal for application monitoring, custom dashboards, and programmatic access
- **Prometheus Format** (`getPrometheusFormattedMetrics()` ) – Perfect for integration with Prometheus/Grafana monitoring stacks
2024-04-14 17:58:26 +02:00
2025-06-09 12:34:06 +00:00
## API Reference
2026-02-19 09:16:43 +00:00
### `new SmartMetrics(logger, sourceName)`
2024-04-14 17:58:26 +02:00
2026-02-19 09:16:43 +00:00
Creates a new SmartMetrics instance.
| Parameter | Type | Description |
|-----------|------|-------------|
| `logger` | `Smartlog` | A `@push.rocks/smartlog` logger instance |
| `sourceName` | `string` | Identifier for your service/application |
### `async getMetrics(): Promise<IMetricsSnapshot>`
2024-04-14 17:58:26 +02:00
2026-02-19 09:16:43 +00:00
Retrieves current system metrics as a structured object.
2024-04-14 17:58:26 +02:00
2026-02-19 09:16:43 +00:00
**Returns `IMetricsSnapshot` :**
2024-04-14 17:58:26 +02:00
```typescript
2025-06-09 12:34:06 +00:00
{
process_cpu_seconds_total: number; // Total CPU time in seconds
2026-02-19 09:46:46 +00:00
nodejs_active_handles_total: number; // Always 0 (deprecated Node.js API; real values tracked by Prometheus default collectors)
nodejs_active_requests_total: number; // Always 0 (deprecated Node.js API; real values tracked by Prometheus default collectors)
2026-02-19 09:16:43 +00:00
nodejs_heap_size_total_bytes: number; // V8 heap size in bytes
cpuPercentage: number; // Aggregated CPU usage across all child processes
cpuUsageText: string; // Human-readable CPU usage (e.g. "12.5 %")
memoryPercentage: number; // Memory usage as percentage of detected limit
memoryUsageBytes: number; // Total memory in bytes across all child processes
memoryUsageText: string; // Human-readable (e.g. "45% | 920 MB / 2 GB")
2024-04-14 17:58:26 +02:00
}
2025-06-09 12:34:06 +00:00
```
2024-04-14 17:58:26 +02:00
2025-06-09 12:34:06 +00:00
**Example:**
2026-02-19 09:16:43 +00:00
2025-06-09 12:34:06 +00:00
```typescript
const metrics = await smartMetrics.getMetrics();
if (metrics.cpuPercentage > 80) {
console.warn('High CPU usage detected!');
}
2024-04-14 17:58:26 +02:00
```
2026-02-19 09:16:43 +00:00
### `start(): void`
Starts automatic metrics collection and heartbeat logging every 20 seconds via the provided `Smartlog` instance.
2024-04-14 17:58:26 +02:00
2025-06-09 12:34:06 +00:00
```typescript
smartMetrics.start();
// Logs: "sending heartbeat for my-service with metrics" every 20 seconds
```
2024-04-14 17:58:26 +02:00
2026-02-19 09:16:43 +00:00
### `stop(): void`
2024-04-14 17:58:26 +02:00
2026-02-19 09:16:43 +00:00
Stops automatic metrics collection, closes heartbeat loop, and shuts down any open Prometheus endpoints.
### `async getPrometheusFormattedMetrics(): Promise<string>`
Returns all metrics in Prometheus text exposition format, including default Node.js collectors and custom SmartMetrics gauges.
2024-04-14 17:58:26 +02:00
```typescript
2025-06-09 12:34:06 +00:00
const promMetrics = await smartMetrics.getPrometheusFormattedMetrics();
// Returns:
// # HELP smartmetrics_cpu_percentage Current CPU usage percentage
// # TYPE smartmetrics_cpu_percentage gauge
// smartmetrics_cpu_percentage 15.2
2026-02-19 09:16:43 +00:00
// # HELP smartmetrics_memory_percentage Current memory usage percentage
// # TYPE smartmetrics_memory_percentage gauge
// smartmetrics_memory_percentage 45.3
// # HELP smartmetrics_memory_usage_bytes Current memory usage in bytes
// # TYPE smartmetrics_memory_usage_bytes gauge
// smartmetrics_memory_usage_bytes 965214208
// ... plus all default Node.js metrics from prom-client
2024-04-14 17:58:26 +02:00
```
2026-02-19 09:16:43 +00:00
### `enablePrometheusEndpoint(port?: number): void`
2024-04-14 17:58:26 +02:00
2026-02-19 09:16:43 +00:00
Starts an HTTP server that exposes metrics at `/metrics` for Prometheus scraping.
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `port` | `number` | `9090` | Port to listen on |
2024-04-14 17:58:26 +02:00
2025-06-09 12:34:06 +00:00
```typescript
smartMetrics.enablePrometheusEndpoint(3000);
2026-02-19 09:16:43 +00:00
// GET http://localhost:3000/metrics → Prometheus text format
// GET http://localhost:3000/anything-else → 404
2025-06-09 12:34:06 +00:00
```
2024-04-14 17:58:26 +02:00
2026-02-19 09:16:43 +00:00
### `disablePrometheusEndpoint(): void`
Gracefully shuts down the Prometheus HTTP server.
### `formatBytes(bytes, decimals?): string`
Utility method to convert byte values to human-readable strings.
```typescript
smartMetrics.formatBytes(1073741824); // "1 GB"
smartMetrics.formatBytes(1536, 1); // "1.5 KB"
```
2024-04-14 17:58:26 +02:00
2025-06-09 12:34:06 +00:00
## Use Cases
2025-06-09 12:07:24 +00:00
2026-02-19 09:16:43 +00:00
### 🔍 Application Performance Monitoring
2025-06-09 12:34:06 +00:00
```typescript
const metricsBefore = await smartMetrics.getMetrics();
await performHeavyOperation();
const metricsAfter = await smartMetrics.getMetrics();
console.log(`Operation consumed ${
metricsAfter.process_cpu_seconds_total - metricsBefore.process_cpu_seconds_total
} CPU seconds`);
```
2025-06-09 12:07:24 +00:00
2026-02-19 09:16:43 +00:00
### 🛡️ Resource Limit Enforcement
2025-06-09 12:07:24 +00:00
```typescript
2025-06-09 12:34:06 +00:00
async function checkResources() {
const metrics = await smartMetrics.getMetrics();
2026-02-19 09:16:43 +00:00
2025-06-09 12:34:06 +00:00
if (metrics.memoryPercentage > 90) {
throw new Error('Memory usage too high, refusing new operations');
}
2026-02-19 09:16:43 +00:00
2025-06-09 12:34:06 +00:00
if (metrics.cpuPercentage > 95) {
await delay(1000); // Back off when CPU is stressed
}
}
```
2025-06-09 12:07:24 +00:00
2026-02-19 09:16:43 +00:00
### 📈 Prometheus + Grafana Stack
2025-06-09 12:34:06 +00:00
```typescript
2026-02-19 09:16:43 +00:00
smartMetrics.enablePrometheusEndpoint(9090);
2025-06-09 12:07:24 +00:00
2026-02-19 09:16:43 +00:00
// prometheus.yml:
2025-06-09 12:34:06 +00:00
// scrape_configs:
// - job_name: 'my-app'
2026-02-19 09:16:43 +00:00
// scrape_interval: 15s
2025-06-09 12:34:06 +00:00
// static_configs:
// - targets: ['localhost:9090']
```
2025-06-09 12:07:24 +00:00
2026-02-19 09:16:43 +00:00
### 🐳 Container Resource Monitoring
2025-06-09 12:07:24 +00:00
2025-06-09 12:34:06 +00:00
```typescript
2026-02-19 09:16:43 +00:00
// Automatically detects Docker/cgroup memory limits
2025-06-09 12:34:06 +00:00
const metrics = await smartMetrics.getMetrics();
console.log(metrics.memoryUsageText);
2026-02-19 09:16:43 +00:00
// Output: "45% | 920 MB / 2 GB" (container limit detected)
2025-06-09 12:07:24 +00:00
```
2026-02-19 09:16:43 +00:00
### 🔄 Health Check Endpoint
2025-06-09 12:34:06 +00:00
```typescript
import express from 'express';
const app = express();
2025-06-09 12:07:24 +00:00
2025-06-09 12:34:06 +00:00
app.get('/health', async (req, res) => {
const metrics = await smartMetrics.getMetrics();
2026-02-19 09:16:43 +00:00
2025-06-09 12:34:06 +00:00
res.json({
status: metrics.memoryPercentage < 90 ? 'healthy' : 'degraded',
2026-02-19 09:16:43 +00:00
cpu: metrics.cpuUsageText,
memory: metrics.memoryUsageText,
2025-06-09 12:34:06 +00:00
});
});
```
2024-04-14 17:58:26 +02:00
2026-02-19 09:16:43 +00:00
### 🔁 Graceful Restart on High Memory (PM2)
2025-06-09 12:34:06 +00:00
```typescript
setInterval(async () => {
const metrics = await smartMetrics.getMetrics();
2026-02-19 09:16:43 +00:00
2025-06-09 12:34:06 +00:00
if (metrics.memoryPercentage > 95) {
console.error('Memory limit reached, requesting restart');
process.exit(0); // PM2 will restart the process
}
}, 10000);
```
2024-04-14 17:58:26 +02:00
## License and Legal Information
2026-02-19 09:16:43 +00:00
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE ](./LICENSE ) file.
2024-04-14 17:58:26 +02:00
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks
2026-02-19 09:16:43 +00:00
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.
Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
2021-08-12 23:19:39 +02:00
2024-04-14 17:58:26 +02:00
### Company Information
2021-08-12 23:19:39 +02:00
2026-02-19 09:16:43 +00:00
Task Venture Capital GmbH
Registered at District Court Bremen HRB 35230 HB, Germany
2021-08-12 23:19:39 +02:00
2026-02-19 09:16:43 +00:00
For any legal inquiries or further information, please contact us via email at hello@task .vc.
2021-08-12 23:19:39 +02:00
2026-02-19 09:16:43 +00:00
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.