fix(deps): bump dependencies, update build script, expand README and npm metadata

This commit is contained in:
2026-02-19 09:16:43 +00:00
parent f67b093127
commit fc017d31b0
6 changed files with 3290 additions and 1648 deletions

View File

@@ -1,5 +1,14 @@
# Changelog
## 2026-02-19 - 2.0.11 - fix(deps)
bump dependencies, update build script, expand README and npm metadata
- Bumped runtime deps: @push.rocks/smartdelay ^3.0.5, @push.rocks/smartlog ^3.1.11
- Updated devDependencies: @git.zone/tsbuild, tsbundle, tsrun, tstest and @types/node versions
- Changed build script: "(tsbuild --web)" → "(tsbuild tsfolders)"
- Updated npmextra.json: renamed keys (gitzone → @git.zone/cli, tsdoc → @git.zone/tsdoc), added release registries and accessLevel, and added @ship.zone/szci entry
- Extensive README improvements: installation notes (pnpm), clearer API docs, examples, added Issue Reporting & Security section and utility docs (formatBytes)
## 2025-06-09 - 2.0.9 - fix(readme)
Update documentation with detailed usage instructions, API references and integration examples.

View File

@@ -1,5 +1,5 @@
{
"gitzone": {
"@git.zone/cli": {
"projectType": "npm",
"module": {
"githost": "code.foss.global",
@@ -25,13 +25,19 @@
"log reporting",
"operational insights"
]
},
"release": {
"registries": [
"https://verdaccio.lossless.digital",
"https://registry.npmjs.org"
],
"accessLevel": "public"
}
},
"npmci": {
"npmGlobalTools": [],
"npmAccessLevel": "public"
},
"tsdoc": {
"@git.zone/tsdoc": {
"legal": "\n## License and Legal Information\n\nThis repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. \n\n**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.\n\n### Trademarks\n\nThis 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 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, and any usage must be approved in writing by Task Venture Capital GmbH.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy 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.\n"
},
"@ship.zone/szci": {
"npmGlobalTools": []
}
}

View File

@@ -9,15 +9,15 @@
"license": "MIT",
"scripts": {
"test": "(tstest test/ --verbose)",
"build": "(tsbuild --web)",
"build": "(tsbuild tsfolders)",
"buildDocs": "tsdoc"
},
"devDependencies": {
"@git.zone/tsbuild": "^2.6.4",
"@git.zone/tsbundle": "^2.0.8",
"@git.zone/tsrun": "^1.2.44",
"@git.zone/tstest": "^2.3.1",
"@types/node": "^22.15.30"
"@git.zone/tsbuild": "^4.1.2",
"@git.zone/tsbundle": "^2.8.3",
"@git.zone/tsrun": "^2.0.1",
"@git.zone/tstest": "^3.1.8",
"@types/node": "^25.3.0"
},
"browserslist": [
"last 1 chrome versions"
@@ -35,8 +35,8 @@
"readme.md"
],
"dependencies": {
"@push.rocks/smartdelay": "^3.0.1",
"@push.rocks/smartlog": "^3.0.2",
"@push.rocks/smartdelay": "^3.0.5",
"@push.rocks/smartlog": "^3.1.11",
"@types/pidusage": "^2.0.2",
"pidtree": "^0.6.0",
"pidusage": "^4.0.1",

4675
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

204
readme.md
View File

@@ -1,6 +1,10 @@
# @push.rocks/smartmetrics
**Powerful system metrics collection for Node.js applications with Prometheus integration**
**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.
## What is SmartMetrics?
@@ -8,17 +12,19 @@ SmartMetrics is a comprehensive metrics collection library that monitors your No
## Key Features
- 📊 **Real-time Metrics Collection** - Monitor CPU and memory usage across all processes
- 🔄 **Automatic Child Process Tracking** - Aggregates metrics from main and child processes
- 🐳 **Docker-Aware** - Detects container memory limits automatically
- 📈 **Prometheus Integration** - Built-in HTTP endpoint for Prometheus scraping
- 🔧 **Flexible Output Formats** - Get metrics as JSON objects or Prometheus text
- 📝 **Automatic Heartbeat Logging** - Optional periodic metrics logging
- 🚀 **Zero Configuration** - Works out of the box with sensible defaults
- 📊 **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
## Installation
```bash
pnpm install @push.rocks/smartmetrics
# or
npm install @push.rocks/smartmetrics
```
@@ -30,9 +36,10 @@ import { Smartlog } from '@push.rocks/smartlog';
// Create a logger instance
const logger = new Smartlog({
logContext: 'my-app',
minimumLogLevel: 'info'
logContext: null,
minimumLogLevel: 'info',
});
logger.enableConsole();
// Initialize SmartMetrics
const metrics = new SmartMetrics(logger, 'my-service');
@@ -46,7 +53,8 @@ console.log(`Memory: ${currentMetrics.memoryUsageText}`);
metrics.start();
// Enable Prometheus endpoint
metrics.enablePrometheusEndpoint(9090); // Metrics available at http://localhost:9090/metrics
metrics.enablePrometheusEndpoint(9090);
// Metrics now available at http://localhost:9090/metrics
// Clean shutdown
metrics.stop();
@@ -55,46 +63,57 @@ metrics.stop();
## Core Concepts
### Process Aggregation
SmartMetrics doesn't just monitor your main process - it automatically discovers and aggregates metrics from all child processes spawned by your application. This gives you a complete picture of your application's resource footprint.
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.
### Memory Limit Detection
The library automatically detects available memory whether running on bare metal, in Docker containers, or with Node.js heap restrictions. It uses the most restrictive limit to ensure accurate percentage calculations.
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()`)
2. **Docker cgroup limit** (`/sys/fs/cgroup/memory/memory.limit_in_bytes`)
3. **V8 heap size limit** (`v8.getHeapStatistics().heap_size_limit`)
This ensures accurate percentage calculations regardless of environment.
### Dual Output Formats
- **JSON Format**: Ideal for application monitoring, custom dashboards, and programmatic access
- **Prometheus Format**: Perfect for integration with Prometheus/Grafana monitoring stacks
- **JSON Format** (`getMetrics()`) Ideal for application monitoring, custom dashboards, and programmatic access
- **Prometheus Format** (`getPrometheusFormattedMetrics()`) Perfect for integration with Prometheus/Grafana monitoring stacks
## API Reference
### Constructor
### `new SmartMetrics(logger, sourceName)`
```typescript
new SmartMetrics(logger: Smartlog, sourceName: string)
```
- `logger`: Smartlog instance for output
- `sourceName`: Identifier for your service/application
Creates a new SmartMetrics instance.
### Methods
| Parameter | Type | Description |
|-----------|------|-------------|
| `logger` | `Smartlog` | A `@push.rocks/smartlog` logger instance |
| `sourceName` | `string` | Identifier for your service/application |
#### `async getMetrics(): Promise<IMetricsSnapshot>`
Retrieves current system metrics as a JSON object.
### `async getMetrics(): Promise<IMetricsSnapshot>`
Retrieves current system metrics as a structured object.
**Returns `IMetricsSnapshot`:**
**Returns:**
```typescript
{
process_cpu_seconds_total: number; // Total CPU time in seconds
nodejs_active_handles_total: number; // Active handles count
nodejs_active_requests_total: number; // Active requests count
nodejs_heap_size_total_bytes: number; // Heap size in bytes
cpuPercentage: number; // Current CPU usage (0-100)
cpuUsageText: string; // Human-readable CPU usage
memoryPercentage: number; // Memory usage percentage
memoryUsageBytes: number; // Memory usage in bytes
memoryUsageText: string; // Human-readable memory usage
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")
}
```
**Example:**
```typescript
const metrics = await smartMetrics.getMetrics();
if (metrics.cpuPercentage > 80) {
@@ -102,51 +121,70 @@ if (metrics.cpuPercentage > 80) {
}
```
#### `start(): void`
Starts automatic metrics collection and heartbeat logging. Logs metrics every 20 seconds.
### `start(): void`
Starts automatic metrics collection and heartbeat logging every 20 seconds via the provided `Smartlog` instance.
**Example:**
```typescript
smartMetrics.start();
// Logs: "sending heartbeat for my-service with metrics" every 20 seconds
```
#### `stop(): void`
Stops automatic metrics collection and closes any open endpoints.
### `stop(): void`
#### `async getPrometheusFormattedMetrics(): Promise<string>`
Returns metrics in Prometheus text exposition format.
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.
**Example:**
```typescript
const promMetrics = await smartMetrics.getPrometheusFormattedMetrics();
// Returns:
// # HELP smartmetrics_cpu_percentage Current CPU usage percentage
// # TYPE smartmetrics_cpu_percentage gauge
// smartmetrics_cpu_percentage 15.2
// ...
// # 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
```
#### `enablePrometheusEndpoint(port?: number): void`
Starts an HTTP server that exposes metrics for Prometheus scraping.
### `enablePrometheusEndpoint(port?: number): void`
**Parameters:**
- `port`: Port number (default: 9090)
Starts an HTTP server that exposes metrics at `/metrics` for Prometheus scraping.
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `port` | `number` | `9090` | Port to listen on |
**Example:**
```typescript
smartMetrics.enablePrometheusEndpoint(3000);
// Metrics now available at http://localhost:3000/metrics
// GET http://localhost:3000/metrics → Prometheus text format
// GET http://localhost:3000/anything-else → 404
```
#### `disablePrometheusEndpoint(): void`
Stops the Prometheus HTTP endpoint.
### `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"
```
## Use Cases
### 1. Application Performance Monitoring
### 🔍 Application Performance Monitoring
```typescript
// Monitor performance during critical operations
const metricsBefore = await smartMetrics.getMetrics();
await performHeavyOperation();
const metricsAfter = await smartMetrics.getMetrics();
@@ -156,9 +194,9 @@ console.log(`Operation consumed ${
} CPU seconds`);
```
### 2. Resource Limit Enforcement
### 🛡️ Resource Limit Enforcement
```typescript
// Prevent operations when resources are constrained
async function checkResources() {
const metrics = await smartMetrics.getMetrics();
@@ -172,38 +210,30 @@ async function checkResources() {
}
```
### 3. Prometheus + Grafana Monitoring
```typescript
// Expose metrics for Prometheus
smartMetrics.enablePrometheusEndpoint();
### 📈 Prometheus + Grafana Stack
// In your Prometheus config:
```typescript
smartMetrics.enablePrometheusEndpoint(9090);
// prometheus.yml:
// scrape_configs:
// - job_name: 'my-app'
// scrape_interval: 15s
// static_configs:
// - targets: ['localhost:9090']
```
### 4. Development and Debugging
```typescript
// Track memory leaks during development
setInterval(async () => {
const metrics = await smartMetrics.getMetrics();
console.log(`Heap: ${metrics.nodejs_heap_size_total_bytes / 1024 / 1024}MB`);
}, 5000);
```
### 🐳 Container Resource Monitoring
### 5. Container Resource Monitoring
```typescript
// Automatically detects container limits
// Automatically detects Docker/cgroup memory limits
const metrics = await smartMetrics.getMetrics();
console.log(metrics.memoryUsageText);
// Output: "45% | 920 MB / 2 GB" (detects container limit)
// Output: "45% | 920 MB / 2 GB" (container limit detected)
```
## Integration Examples
### 🔄 Health Check Endpoint
### With Express
```typescript
import express from 'express';
@@ -214,17 +244,15 @@ app.get('/health', async (req, res) => {
res.json({
status: metrics.memoryPercentage < 90 ? 'healthy' : 'degraded',
metrics: {
cpu: metrics.cpuUsageText,
memory: metrics.memoryUsageText
}
memory: metrics.memoryUsageText,
});
});
```
### With PM2
### 🔁 Graceful Restart on High Memory (PM2)
```typescript
// Graceful shutdown on high memory
setInterval(async () => {
const metrics = await smartMetrics.getMetrics();
@@ -235,37 +263,23 @@ setInterval(async () => {
}, 10000);
```
### With Custom Dashboards
```typescript
// Stream metrics to your monitoring service
setInterval(async () => {
const metrics = await smartMetrics.getMetrics();
await sendToMonitoringService({
timestamp: Date.now(),
service: 'my-service',
cpu: metrics.cpuPercentage,
memory: metrics.memoryUsageBytes,
memoryLimit: metrics.memoryUsageBytes / (metrics.memoryPercentage / 100)
});
}, 60000);
```
## License and Legal Information
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file.
**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
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 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, and any usage must be approved in writing by Task Venture Capital GmbH.
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.
### Company Information
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
Registered at District Court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
For any legal inquiries or further information, please contact us via email at hello@task.vc.
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.

View File

@@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@push.rocks/smartmetrics',
version: '2.0.9',
version: '2.0.11',
description: 'A package for easy collection and reporting of system and process metrics.'
}