### Install system-monitoring Package Source: https://www.npmjs.com/package/system-monitoring/v/0.0_activeTab=dependencies Installs the system-monitoring package using npm or yarn. This is the initial step before using any of its functionalities. ```bash npm install system-monitoring ``` ```bash yarn add system-monitoring ``` -------------------------------- ### Install npm Package Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=code Instructions to install the system-monitoring package using npm. ```bash npm i system-monitoring ``` -------------------------------- ### CPU Information Example Response Source: https://www.npmjs.com/package/system-monitoring/v/0.0 An example JSON response structure for CPU information obtained from the system-monitoring package. It includes overall usage and details for each CPU core. ```json { "totalUserTime": 123456, "totalSystemTime": 654321, "totalIdleTime": 789012, "totalTime": 1567890, "usedTime": 777777, "idleTime": 789012, "usagePercentage": 49.5, "coreDetails": [ { "coreId": 0, "userTime": 12345, "systemTime": 6543, "idleTime": 7890, "totalTime": 15678, "usagePercentage": 51.4 } // more cores... ] } ``` -------------------------------- ### System Monitoring API Examples Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=readme Examples demonstrating the usage of various system monitoring functions. These functions provide insights into CPU, memory, disk, network, OS, and process information. Response formats vary based on the specific metric being retrieved. ```javascript // Get CPU Information const cpuInfo = await systemMonitor.getCpuInfo(); console.log(cpuInfo); // Get Memory Usage const memoryUsage = await systemMonitor.getMemoryUsage(); console.log(memoryUsage); // Get Disk Usage const diskUsage = await systemMonitor.getDiskUsage(); console.log(diskUsage); // Get System Uptime const uptime = await systemMonitor.getSystemUptime(); console.log(`System Uptime: ${uptime} seconds`); // Get OS Information const osInfo = await systemMonitor.getOSInfo(); console.log(osInfo); // Get Process Info const processInfo = await systemMonitor.getProcessInfo(); console.log(processInfo); // Get Load Average const loadAvg = await systemMonitor.getLoadAverage(); console.log(loadAvg); // Get User Info const userInfo = await systemMonitor.getUserInfo(); console.log(userInfo); // Get Temperature (if supported) const temperature = await systemMonitor.getTemperature(); if (temperature) { console.log(`System Temperature: ${temperature}°C`); } // Get File System Info const fsInfo = await systemMonitor.getFileSystemInfo(); console.log(fsInfo); // Get Active Connections const connections = await systemMonitor.getActiveConnections(); console.log(connections); // Get Scheduled Tasks const tasks = await systemMonitor.getScheduledTasks(); console.log(tasks); // Get Service Status const serviceStatus = await systemMonitor.getServiceStatus('your_service_name'); console.log(serviceStatus); // Get Logs with Keyword const logs = await systemMonitor.getLogs('/var/log/app.log', 'error'); console.log(logs); ``` -------------------------------- ### CPU Information Example Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=code An example JSON response detailing CPU usage. It includes total user, system, and idle times, along with usage percentages. It also provides detailed statistics for each CPU core. ```json { "totalUserTime": 123456, "totalSystemTime": 654321, "totalIdleTime": 789012, "totalTime": 1567890, "usedTime": 777777, "idleTime": 789012, "usagePercentage": 49.5, "coreDetails": [ { "coreId": 0, "userTime": 12345, "systemTime": 6543, "idleTime": 7890, "totalTime": 15678, "usagePercentage": 51.4 } ] } ``` -------------------------------- ### Install System Monitor Package Source: https://www.npmjs.com/package/system-monitoring/v/0.0_activeTab=dependents Install the system-monitoring package using npm or yarn. This is the first step to integrating system monitoring capabilities into your Node.js application. ```bash npm install system-monitoring ## Or yarn add system-monitoring ``` -------------------------------- ### Disk Usage Example Response Source: https://www.npmjs.com/package/system-monitoring/v/0.0 An example JSON response structure for disk usage obtained from the system-monitoring package. It details the total, used, and available disk space in bytes. ```json { "total": 104857600, "used": 52428800, "available": 52428800 } ``` -------------------------------- ### Example JSON Log Entry for TrackTime Middleware Source: https://www.npmjs.com/package/system-monitoring/index This is an example of a single log entry generated by the trackTime middleware when the 'filePath' option is configured. Each entry is a JSON object appended to the log file. ```json {"method":"GET","url":"/","responseTime":"12.345","timestamp":"2024-09-15T10:30:00.123Z"} ``` -------------------------------- ### System Monitoring API Examples Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=versions These examples demonstrate how to use the system monitoring APIs to retrieve various system metrics. Each function returns specific information about the system's performance and configuration. Ensure necessary permissions are available for accessing certain system details. ```javascript // Get CPU Information const cpuInfo = await getCpuInfo(); console.log(cpuInfo); // Get Memory Usage const memoryUsage = await getMemoryUsage(); console.log(memoryUsage); // Get Disk Usage const diskUsage = await getDiskUsage(); console.log(diskUsage); // Get Network Information const networkInfo = await getNetworkInfo(); console.log(networkInfo); // Get System Uptime const uptime = await getSystemUptime(); console.log(`System uptime: ${uptime} seconds`); // Get Process Info const processInfo = await getProcessInfo(); console.log(processInfo); // Get OS Info const osInfo = await getOSInfo(); console.log(osInfo); // Get Load Average const loadAverage = await getLoadAverage(); console.log(loadAverage); // Get User Info const userInfo = await getUserInfo(); console.log(userInfo); // Get Temperature (if supported) const temperature = await getTemperature(); console.log(temperature); // Get File System Info const fileSystemInfo = await getFileSystemInfo(); console.log(fileSystemInfo); // Get Active Connections const activeConnections = await getActiveConnections(); console.log(activeConnections); // Get Scheduled Tasks const scheduledTasks = await getScheduledTasks(); console.log(scheduledTasks); // Get Service Status const serviceStatus = await getServiceStatus('nginx'); console.log(serviceStatus); // Get Logs with keyword const logs = await getLogs('/var/log/syslog', 'error'); console.log(logs); ``` -------------------------------- ### Memory Usage Example Response Source: https://www.npmjs.com/package/system-monitoring/v/0.0 An example JSON response structure for memory usage obtained from the system-monitoring package. It provides the total, free, and used memory in bytes. ```json { "totalMemory": 16777216, "freeMemory": 8388608, "usedMemory": 8388608 } ``` -------------------------------- ### Example Custom Database Storage Function using MongoDB Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=dependencies Provides an example implementation of a custom database storage function using the MongoDB Node.js driver. This function connects to a MongoDB instance, inserts log data into a specified collection, and then closes the connection. ```typescript import { MongoClient } from 'mongodb'; // Assuming LogData interface is defined as above interface LogData { method: string; url: string; responseTime: string; timestamp: string; } async function storeLogInDb(logData: LogData) { const client = await MongoClient.connect('mongodb://localhost:27017'); const db = client.db('logsDatabase'); await db.collection('requestLogs').insertOne(logData); await client.close(); } // This function can then be passed to the trackTime middleware: // app.use(trackTime({ storeOnDb: storeLogInDb })); ``` -------------------------------- ### trackTime Middleware Database Logging Example (MongoDB) Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=code Demonstrates how to implement a custom database storage function for the trackTime middleware, specifically for logging request data to a MongoDB database. This example connects to MongoDB, inserts log data, and closes the connection. ```typescript // Example function to store log data in a MongoDB database import { MongoClient } from 'mongodb'; interface LogData { method: string; // HTTP method (e.g., GET, POST) url: string; // The URL requested responseTime: string; // Time taken to process the request in milliseconds timestamp: string; // ISO timestamp when the request was made } async function storeLogInDb(logData: LogData) { const client = await MongoClient.connect('mongodb://localhost:27017'); const db = client.db('logsDatabase'); await db.collection('requestLogs').insertOne(logData); await client.close(); } // Pass this function to the `trackTime` middleware // app.use(trackTime({ storeOnDb: storeLogInDb })); ``` -------------------------------- ### Get OS Information Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=dependencies Retrieves detailed information about the operating system, such as the name, version, and architecture. ```javascript getOSInfo() ``` -------------------------------- ### Example MongoDB Database Storage Function for TrackTime (TypeScript) Source: https://www.npmjs.com/package/system-monitoring/index This example demonstrates how to implement a custom database storage function using MongoClient to store log data in a MongoDB collection. This function can be passed to the trackTime middleware via the 'storeOnDb' option. ```typescript // Example function to store log data in a MongoDB database import { MongoClient } from 'mongodb'; async function storeLogInDb(logData: LogData) { const client = await MongoClient.connect('mongodb://localhost:27017'); const db = client.db('logsDatabase'); await db.collection('requestLogs').insertOne(logData); await client.close(); } // Pass this function to the `trackTime` middleware app.use(trackTime({ storeOnDb: storeLogInDb })); ``` -------------------------------- ### Custom Database Storage Function Example with MongoDB Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=versions An example of a custom asynchronous function to store log data in a MongoDB database using the MongoClient. This function can be passed to the `trackTime` middleware's `storeOnDb` option. ```typescript // Example function to store log data in a MongoDB database import { MongoClient } from 'mongodb'; async function storeLogInDb(logData: LogData) { const client = await MongoClient.connect('mongodb://localhost:27017'); const db = client.db('logsDatabase'); await db.collection('requestLogs').insertOne(logData); await client.close(); } // Pass this function to the `trackTime` middleware // app.use(trackTime({ storeOnDb: storeLogInDb })); ``` -------------------------------- ### Get User Information Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=dependencies Retrieves extended user information and system details related to the current user context. ```javascript getUserInfo() ``` -------------------------------- ### Configure trackTime Middleware with File and Database Logging Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=readme This example shows advanced configuration of the `trackTime` middleware, including a custom asynchronous function for storing logs in a MongoDB database. It utilizes the `filePath` option for file logging and the `storeOnDb` callback for database persistence. ```typescript // Example function to store log data in a MongoDB database import { MongoClient } from 'mongodb'; interface LogData { method: string; url: string; responseTime: string; timestamp: string; } async function storeLogInDb(logData: LogData) { const client = await MongoClient.connect('mongodb://localhost:27017'); const db = client.db('logsDatabase'); await db.collection('requestLogs').insertOne(logData); await client.close(); } // Assuming 'app' is your Express application instance // app.use(trackTime({ storeOnDb: storeLogInDb })); ``` -------------------------------- ### Get Logs with Keyword Filter Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=dependencies Fetches log entries from a specified file path, with an optional keyword filter to narrow down the results. The file path must exist and be writable. If the path doesn't exist, the middleware will attempt to create it. ```javascript getLogs(path, keyword) ``` -------------------------------- ### Get File System Information Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=dependencies Retrieves comprehensive information about the file system, including disk space usage statistics. ```javascript getFileSystemInfo() ``` -------------------------------- ### Get CPU Information Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=dependencies Retrieves CPU usage details for all cores and the system as a whole. Returns an object containing total user time, system time, idle time, total time, used time, and usage percentage, along with detailed information for each core. ```javascript getCpuInfo() ``` -------------------------------- ### Implement trackTime Middleware for Response Time Logging Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=readme The `trackTime` middleware for Express.js tracks the response time for each request. It offers options to log data to a file and/or to a database via a callback function. This example demonstrates basic usage with file logging and a database callback. ```typescript import express from 'express'; import { trackTime } from './middlewares/trackTime'; const app = express(); function storeOnDb(logData: { method: string; url: string; responseTime: string; timestamp: string }) { console.log('Storing log in the database:', logData); } app.use(trackTime({ filePath: './logs/request_logs.txt', storeOnDb: storeOnDb })); app.get('/', (req, res) => { res.send('Hello, World!'); }); app.listen(3000, () => { console.log('Server is running on port 3000'); }); ``` -------------------------------- ### Get System Uptime Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=dependencies Returns the system uptime in seconds. This indicates how long the system has been running since the last reboot. ```javascript getSystemUptime() ``` -------------------------------- ### Get System Temperature Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=dependencies Returns the system temperature readings, if the hardware and operating system support it. This is typically available on Linux and Windows systems. ```javascript getTemperature() ``` -------------------------------- ### Get Network Information Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=dependencies Returns details about all network interfaces on the system. The specific structure of the returned data may vary depending on the operating system. ```javascript getNetworkInfo() ``` -------------------------------- ### Get Disk Usage Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=dependencies Fetches disk usage statistics for the file system. Returns an object with total, used, and available space, typically in bytes. ```javascript getDiskUsage() ``` -------------------------------- ### Get Process Information Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=dependencies Provides the CPU and memory usage of the current running process. This is useful for monitoring the resource consumption of the application itself. ```javascript getProcessInfo() ``` -------------------------------- ### Get Service Status Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=dependencies Retrieves the status of a specified service. This requires the service name as input and returns its current operational state. ```javascript getServiceStatus(serviceName) ``` -------------------------------- ### Get Load Average Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=dependencies Retrieves the system load averages over the last 1, 5, and 15 minutes. This provides an indication of the system's current workload. ```javascript getLoadAverage() ``` -------------------------------- ### Get Logs Functionality Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=dependents The `getLogs` function retrieves log entries from a specified file path. It supports an optional keyword to filter the log entries, returning only those lines that contain the specified keyword. ```javascript // Example usage within the systemMonitor middleware options: // logs: { path: '/var/log/app.log', keyword: 'error' } ``` -------------------------------- ### Basic System Monitoring with JavaScript Source: https://www.npmjs.com/package/system-monitoring/v/0.0_activeTab=dependents Demonstrates basic usage of the system-monitoring library to fetch CPU, memory, and disk usage. It utilizes Promises to handle asynchronous operations for CPU and memory, while disk usage is fetched synchronously. ```javascript import { getCpuInfo, getMemoryUsage, getDiskUsage } from 'system-monitoring'; // Get CPU information getCpuInfo().then(cpuInfo => { console.log('CPU Information:', cpuInfo); }); // Get memory usage getMemoryUsage().then(memoryUsage => { console.log('Memory Usage:', memoryUsage); }); // Get disk usage const diskUsage = getDiskUsage(); console.log('Disk Usage:', diskUsage); ``` -------------------------------- ### Contributing to System Monitoring Source: https://www.npmjs.com/package/system-monitoring/v/0.0 Guidelines for contributing to the system monitoring project, including bug reports, suggestions, feature requests, and the contribution workflow. ```APIDOC ## Contributing to System Monitoring ### Description Contributions are welcome! If you have any bug reports, suggestions, or feature requests, please open an issue on GitHub. Follow the steps below to contribute. ### Workflow 1. **Fork the repository** 2. **Create a new feature branch** (`git checkout -b feature/new-feature`) 3. **Commit your changes** (`git commit -m 'Add new feature'`) 4. **Push to the branch** (`git push origin feature/new-feature`) 5. **Create a new Pull Request** Make sure to follow the Contributor Covenant Code of Conduct when participating in the project. ``` -------------------------------- ### Express Middleware for System Monitoring Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=readme Sets up an Express server with various system monitoring middleware. It includes middleware for tracking response times, errors, and general system metrics (CPU, memory, disk). Metrics are accessible via request objects. ```javascript import express from 'express'; import { systemMonitor, trackRequestResponseTime, createErrorTrackingMiddleware } from 'system-monitoring'; const errorTrackingMiddleware: ReturnType = createErrorTrackingMiddleware(); const app = express(); // Middleware to track response time app.use(trackRequestResponseTime()); // the time will append on the response header X-Response-Time // track error rate app.use(errorTrackingMiddleware) // access information by req.errorResponse // System monitor middleware app.use(systemMonitor({ cpu: true, memory: true, disk: true })); // access information by req.systemMetrics app.get('/', (req, res) => { res.send('System monitoring active.'); }); app.listen(3000, () => { console.log('Server is running on port 3000'); }); ``` -------------------------------- ### Express Middlewares Source: https://www.npmjs.com/package/system-monitoring/v/0.0_activeTab=dependencies Documentation for the Express.js middleware functions provided by the system-monitoring package. ```APIDOC ## Express Middlewares This package provides middleware functions for Express.js applications. ### `systemMonitor(options)` #### Description This middleware collects and exposes system metrics (CPU, memory, disk usage) to `req.systemMetrics`. #### Method `app.use()` #### Parameters - **options** (object) - Configuration options. - **cpu** (boolean) - `true` to enable CPU monitoring, `false` otherwise. - **memory** (boolean) - `true` to enable memory monitoring, `false` otherwise. - **disk** (boolean) - `true` to enable disk monitoring, `false` otherwise. #### Request Body None #### Response - **req.systemMetrics** (object) - An object containing the collected system metrics. ### `trackRequestResponseTime()` #### Description This middleware tracks the response time of requests and appends it to the `X-Response-Time` header. #### Method `app.use()` #### Parameters None #### Request Body None #### Response - **X-Response-Time** (header) - The time taken to process the request in milliseconds. ### `createErrorTrackingMiddleware()` #### Description This middleware tracks errors and makes error-related information available via `req.errorResponse`. #### Method `app.use()` #### Parameters None #### Request Body None #### Response - **req.errorResponse** (object) - An object containing error tracking information. ### Request Example ```javascript import express from 'express'; import { systemMonitor, trackRequestResponseTime, createErrorTrackingMiddleware } from 'system-monitoring'; const app = express(); const errorTrackingMiddleware = createErrorTrackingMiddleware(); app.use(trackRequestResponseTime()); app.use(errorTrackingMiddleware); app.use(systemMonitor({ cpu: true, memory: true, disk: true })); app.get('/', (req, res) => { // Access metrics via req.systemMetrics console.log(req.systemMetrics); // Access error info via req.errorResponse (after an error occurs) console.log(req.errorResponse); res.send('System monitoring active.'); }); app.listen(3000, () => { console.log('Server is running on port 3000'); }); ``` ``` -------------------------------- ### System Monitor Middleware Configuration Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=versions Configure the `systemMonitor` middleware to enable or disable specific monitoring functionalities. Options include CPU, memory, disk, network, uptime, process info, temperature, OS info, load average, user info, file system info, active connections, scheduled tasks, and log fetching. Set `temperature` to true only on Linux/Windows systems where supported. Log fetching requires a `path` and an optional `keyword`. ```javascript const express = require('express'); const { systemMonitor } = require('your-npm-package-name'); const app = express(); app.use(systemMonitor({ cpu: true, memory: true, disk: true, network: true, uptime: true, processInfo: true, temperature: false, // Set to true if supported and needed osInfo: false, loadAverage: false, userInfo: false, fileSystemInfo: false, activeConnections: false, scheduledTasks: false, logs: { path: '/var/log/app.log', keyword: 'error' }, responseTime: true })); // ... other middleware and routes ``` -------------------------------- ### Get Active Network Connections Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=dependencies Retrieves a list of active network connections on the system. This can be useful for network monitoring and security analysis. ```javascript getActiveConnections() ``` -------------------------------- ### System Monitoring Middleware Options Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=dependents The `systemMonitor` middleware accepts an options object to selectively enable various monitoring functionalities. These include CPU, memory, disk, network, uptime, process info, temperature, OS info, load average, user info, file system info, active connections, scheduled tasks, logs, and response time tracking. ```javascript const systemMonitor = require('system-monitoring'); app.use(systemMonitor({ cpu: true, memory: true, disk: true, network: true, uptime: true, processInfo: true, temperature: false, // Enable only on Linux/Windows osInfo: false, loadAverage: false, userInfo: false, fileSystemInfo: false, activeConnections: false, scheduledTasks: false, logs: { path: '/var/log/app.log', keyword: 'error' }, responseTime: true })); ``` -------------------------------- ### System Monitoring Functions Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=code This section details the various functions available for retrieving system performance metrics. ```APIDOC ## System Monitoring Functions API ### Description Provides a collection of functions to retrieve detailed system performance and information. ### Functions - **getCpuInfo()**: Returns CPU usage details for all cores and the system as a whole. - **getMemoryUsage()**: Retrieves total, free, and used memory information. - **getDiskUsage()**: Fetches disk usage statistics including total, used, and available space. - **getNetworkInfo()**: Returns details about all network interfaces. - **getSystemUptime()**: Returns the system uptime in seconds. - **getProcessInfo()**: Provides the CPU and memory usage of the current process. - **getOSInfo()**: Retrieves detailed information about the operating system. - **getLoadAverage()**: Retrieves the system load averages over 1, 5, and 15 minutes. - **getUserInfo()**: Retrieves extended user information and system details. - **getTemperature()**: Returns the system temperature (if supported). - **getFileSystemInfo()**: Retrieves information about the file system, including disk space usage. - **getActiveConnections()**: Retrieves the active network connections on the system. - **getScheduledTasks()**: Retrieves a list of scheduled tasks from the system and parses them into an object. - **getServiceStatus(serviceName)**: Retrieves the status of a given service. - **getLogs(path, keyword)**: Fetches logs from the specified file, optionally filtering by a keyword. ### Request Body (Not applicable for most functions, except `getLogs`) ### Response Examples #### CPU Information Response Example ```json { "totalUserTime": 123456, "totalSystemTime": 654321, "totalIdleTime": 789012, "totalTime": 1567890, "usedTime": 777777, "idleTime": 789012, "usagePercentage": 49.5, "coreDetails": [ { "coreId": 0, "userTime": 12345, "systemTime": 6543, "idleTime": 7890, "totalTime": 15678, "usagePercentage": 51.4 } ] } ``` #### Memory Usage Response Example ```json { "totalMemory": 16777216, "freeMemory": 8388608, "usedMemory": 8388608 } ``` #### Disk Usage Response Example ```json { "total": 104857600, "used": 52428800, "available": 52428800 } ``` #### Get Logs Request Parameters - **path** (string) - Required - The path to the log file. - **keyword** (string) - Optional - A keyword to filter log entries. #### Get Logs Response Example ```json [ "Log entry 1 with keyword", "Another log entry" ] ``` ``` -------------------------------- ### System Monitoring Functions Source: https://www.npmjs.com/package/system-monitoring/v/0.0_activeTab=versions This section details the core functions available in the system-monitoring package for retrieving various system metrics. ```APIDOC ## GET /api/system/cpu ### Description Retrieves detailed CPU usage information for all cores and the system as a whole. ### Method GET ### Endpoint /api/system/cpu ### Parameters None ### Request Example None ### Response #### Success Response (200) - **cpuInfo** (object) - Object containing CPU usage details. - **totalUserTime** (number) - Total user time in milliseconds. - **totalSystemTime** (number) - Total system time in milliseconds. - **totalIdleTime** (number) - Total idle time in milliseconds. - **totalTime** (number) - Total CPU time in milliseconds. - **usedTime** (number) - Total used CPU time in milliseconds. - **idleTime** (number) - Total idle CPU time in milliseconds. - **usagePercentage** (number) - Overall CPU usage percentage. - **coreDetails** (array) - Array of objects, each representing a CPU core's details. - **coreId** (number) - The ID of the CPU core. - **userTime** (number) - User time for the core. - **systemTime** (number) - System time for the core. - **idleTime** (number) - Idle time for the core. - **totalTime** (number) - Total time for the core. - **usagePercentage** (number) - CPU usage percentage for the core. #### Response Example ```json { "totalUserTime": 123456, "totalSystemTime": 654321, "totalIdleTime": 789012, "totalTime": 1567890, "usedTime": 777777, "idleTime": 789012, "usagePercentage": 49.5, "coreDetails": [ { "coreId": 0, "userTime": 12345, "systemTime": 6543, "idleTime": 7890, "totalTime": 15678, "usagePercentage": 51.4 } ] } ``` ## GET /api/system/memory ### Description Retrieves total, free, and used memory statistics for the system. ### Method GET ### Endpoint /api/system/memory ### Parameters None ### Request Example None ### Response #### Success Response (200) - **memoryUsage** (object) - Object containing memory statistics. - **totalMemory** (number) - Total system memory in bytes. - **freeMemory** (number) - Free system memory in bytes. - **usedMemory** (number) - Used system memory in bytes. #### Response Example ```json { "totalMemory": 16777216, "freeMemory": 8388608, "usedMemory": 8388608 } ``` ## GET /api/system/disk ### Description Fetches disk usage statistics including total, used, and available space for the root filesystem. ### Method GET ### Endpoint /api/system/disk ### Parameters None ### Request Example None ### Response #### Success Response (200) - **diskUsage** (object) - Object containing disk usage statistics. - **total** (number) - Total disk space in bytes. - **used** (number) - Used disk space in bytes. - **available** (number) - Available disk space in bytes. #### Response Example ```json { "total": 104857600, "used": 52428800, "available": 52428800 } ``` ## GET /api/system/network ### Description Returns details about all network interfaces on the system. ### Method GET ### Endpoint /api/system/network ### Parameters None ### Request Example None ### Response #### Success Response (200) - **networkInfo** (object) - Object containing network interface details. - **(interfaceName)** (object) - Details for each network interface. - **mac** (string) - MAC address of the interface. - **ip4** (string) - IPv4 address of the interface. - **ip6** (string) - IPv6 address of the interface. - **type** (string) - Type of the interface (e.g., 'Ethernet', 'Loopback'). - **operstate** (string) - Operational state of the interface (e.g., 'up', 'down'). - **rxBytes** (number) - Received bytes. - **txBytes** (number) - Transmitted bytes. - **rxPackets** (number) - Received packets. - **txPackets** (number) - Transmitted packets. #### Response Example ```json { "eth0": { "mac": "00:01:02:03:04:05", "ip4": "192.168.1.100", "ip6": "::1", "type": "Ethernet", "operstate": "up", "rxBytes": 123456789, "txBytes": 987654321, "rxPackets": 100000, "txPackets": 90000 } } ``` ## GET /api/system/uptime ### Description Returns the system uptime in seconds. ### Method GET ### Endpoint /api/system/uptime ### Parameters None ### Request Example None ### Response #### Success Response (200) - **uptimeSeconds** (number) - The system uptime in seconds. #### Response Example ```json { "uptimeSeconds": 3600 } ``` ## GET /api/process/info ### Description Provides the CPU and memory usage of the current Node.js process. ### Method GET ### Endpoint /api/process/info ### Parameters None ### Request Example None ### Response #### Success Response (200) - **processInfo** (object) - Object containing process CPU and memory usage. - **cpuUsage** (number) - CPU usage percentage of the process. - **memoryUsage** (number) - Memory usage in bytes of the process. #### Response Example ```json { "cpuUsage": 5.2, "memoryUsage": 104857600 } ``` ## GET /api/system/temperature ### Description Returns the current temperature of the system, if supported by the hardware. ### Method GET ### Endpoint /api/system/temperature ### Parameters None ### Request Example None ### Response #### Success Response (200) - **temperatureCelsius** (number) - The system temperature in degrees Celsius. #### Response Example ```json { "temperatureCelsius": 45.5 } ``` ## POST /api/system/logs ### Description Fetches system logs from a specified file, with optional keyword filtering. ### Method POST ### Endpoint /api/system/logs ### Parameters #### Request Body - **path** (string) - Required - The path to the log file. - **keyword** (string) - Optional - A keyword to filter the log entries. ### Request Example ```json { "path": "/var/log/syslog", "keyword": "error" } ``` ### Response #### Success Response (200) - **logEntries** (array) - An array of log entries matching the criteria. - **(string)** - Each element is a string representing a log line. #### Response Example ```json { "logEntries": [ "2023-10-27 10:00:00 ERROR: Disk space low.", "2023-10-27 10:05:00 WARNING: High CPU usage detected." ] } ``` ``` -------------------------------- ### Get Scheduled Tasks Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=dependencies Retrieves a list of scheduled tasks from the system and parses them into a structured object. This function is specific to systems that manage scheduled tasks. ```javascript getScheduledTasks() ``` -------------------------------- ### System Monitor Middleware Options Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=readme Configuration options for the `systemMonitor` middleware. These boolean flags enable or disable specific monitoring metrics. Some options, like `temperature` and `osInfo`, may have platform-specific limitations. The `logs` option allows specifying a file path and an optional keyword for filtering. ```javascript const systemMonitor = require('your-npm-package'); // Replace with actual package name app.use(systemMonitor.systemMonitor({ cpu: true, memory: true, disk: true, network: false, uptime: true, processInfo: true, temperature: true, // Only on Linux/Windows osInfo: false, loadAverage: false, userInfo: false, fileSystemInfo: false, activeConnections: false, scheduledTasks: false, logs: { path: '/path/to/your/logfile.log', keyword: 'WARN' }, responseTime: true })); ``` -------------------------------- ### Get Memory Usage Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=dependencies Retrieves system memory information, including total, free, and used memory. The output is an object representing memory in bytes. ```javascript getMemoryUsage() ``` -------------------------------- ### Configure TrackTime Middleware Options and Log Data Structure Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=dependencies Details the configuration options for the `trackTime` middleware, including `filePath` for file logging and `storeOnDb` for custom database persistence. It also defines the `LogData` interface specifying the structure of the data passed to these logging mechanisms. ```typescript // Log Data Structure interface LogData { method: string; // HTTP method (e.g., GET, POST) url: string; // The URL requested responseTime: string; // Time taken to process the request in milliseconds timestamp: string; // ISO timestamp when the request was made } // Example usage within app.use(trackTime({...})) /* app.use(trackTime({ filePath: './logs/request_logs.txt', // Path for file logging storeOnDb: (logData: LogData) => { // Callback for database storage // Your database storage logic here console.log('Log data:', logData); } })); */ ``` -------------------------------- ### System Monitor Middleware Options Source: https://www.npmjs.com/package/system-monitoring/v/0.0 Configuration options for the `systemMonitor` middleware to enable or disable various monitoring features. ```APIDOC ## System Monitor Middleware Options ### Description The `systemMonitor` middleware accepts an object with the following options to configure monitoring features. ### Parameters #### Request Body Options - **`cpu`** (boolean) - Optional - Default: `true` - Enable CPU usage monitoring. - **`memory`** (boolean) - Optional - Default: `true` - Enable memory usage monitoring. - **`disk`** (boolean) - Optional - Default: `true` - Enable disk usage monitoring. - **`network`** (boolean) - Optional - Default: `true` - Enable network interface information monitoring. - **`uptime`** (boolean) - Optional - Default: `true` - Enable system uptime monitoring. - **`processInfo`** (boolean) - Optional - Default: `true` - Enable process CPU and memory usage monitoring. - **`temperature`** (boolean) - Optional - Default: `false` - Enable system temperature monitoring (only on Linux/Windows). - **`logs`** ({ path: string, keyword?: string }) - Optional - Default: `null` - Fetch logs from a specified file, optionally filtered by keyword. - **`responseTime`** (boolean) - Optional - Default: `false` - Track response time for each request. ### Request Example ```json { "cpu": true, "memory": true, "disk": false, "network": true, "uptime": true, "processInfo": true, "temperature": false, "logs": { "path": "/var/log/syslog", "keyword": "error" }, "responseTime": true } ``` ### Response This middleware typically does not return a specific response body for its configuration. Its effects are on system monitoring and potentially request handling (e.g., response time tracking). ``` -------------------------------- ### System Monitoring Middleware Configuration Source: https://www.npmjs.com/package/system-monitoring/index Configuration options for the `systemMonitor` middleware. This middleware allows enabling or disabling specific monitoring metrics like CPU, memory, disk, network, uptime, process info, temperature, OS info, load average, user info, file system info, active connections, scheduled tasks, and log fetching. ```javascript app.use(systemMonitor({ cpu: true, memory: true, disk: true, network: true, uptime: true, processInfo: true, temperature: false, // Only on Linux/Windows osInfo: false, loadAverage: false, userInfo: false, fileSystemInfo: false, activeConnections: false, scheduledTasks: false, logs: { path: '/var/log/syslog', keyword: 'error' }, responseTime: true })); ``` -------------------------------- ### System Monitor Middleware Configuration Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=code The systemMonitor middleware gathers various system metrics. It accepts an options object to enable or disable specific monitoring features like CPU, memory, disk, network, uptime, process info, temperature, OS info, load average, user info, file system info, active connections, scheduled tasks, and log fetching. ```javascript app.use(systemMonitor({ cpu: true, memory: true, disk: true, network: true, uptime: true, processInfo: true, temperature: false, osInfo: false, loadAverage: false, userInfo: false, fileSystemInfo: false, activeConnections: false, scheduledTasks: false, logs: { path: './logs/app.log', keyword: 'error' }, responseTime: true })); ``` -------------------------------- ### Express Middlewares for System Monitoring Source: https://www.npmjs.com/package/system-monitoring/v/0.0_activeTab=dependencies Integrates system-monitoring functionalities as Express middleware for tracking response times, errors, and system metrics. It configures specific metrics to be tracked and exposes them via `req.systemMetrics`. ```javascript import express from 'express'; import { systemMonitor, trackRequestResponseTime, createErrorTrackingMiddleware } from 'system-monitoring'; const errorTrackingMiddleware = createErrorTrackingMiddleware(); const app = express(); // Middleware to track response time app.use(trackRequestResponseTime()); // time is appended to the response header X-Response-Time // track error rate app.use(errorTrackingMiddleware); // access information by req.errorResponse // System monitor middleware app.use(systemMonitor({ cpu: true, memory: true, disk: true })); // access information by req.systemMetrics app.get('/', (req, res) => { res.send('System monitoring active.'); }); app.listen(3000, () => { console.log('Server is running on port 3000'); }); ``` -------------------------------- ### Express Middlewares Source: https://www.npmjs.com/package/system-monitoring/v/0.0 Documentation for the Express.js middleware functions provided by the system-monitoring package to integrate system metrics into web applications. ```APIDOC ## Express Middlewares ### `systemMonitor(options)` #### Description Express middleware to gather and expose system metrics. Metrics are attached to the `req.systemMetrics` object. #### Method `USE` (Express middleware) #### Endpoint N/A (Used within an Express app) #### Parameters - **`options`** (object) - Optional - Configuration object for the middleware. - **`cpu`** (boolean) - `true` to include CPU metrics, `false` otherwise. - **`memory`** (boolean) - `true` to include memory metrics, `false` otherwise. - **`disk`** (boolean) - `true` to include disk metrics, `false` otherwise. #### Request Body N/A #### Request Example ```javascript import express from 'express'; import { systemMonitor } from 'system-monitoring'; const app = express(); app.use(systemMonitor({ cpu: true, memory: true, disk: true })); app.get('/', (req, res) => { // Access metrics via req.systemMetrics console.log(req.systemMetrics); res.send('System monitoring active.'); }); app.listen(3000, () => { console.log('Server is running on port 3000'); }); ``` #### Response ##### Success Response (200) - **`req.systemMetrics`** (object) - An object containing the requested system metrics (e.g., `cpu`, `memory`, `disk`). ### `trackRequestResponseTime()` #### Description Middleware to track the response time of requests. The time is appended to the `X-Response-Time` response header. #### Method `USE` (Express middleware) #### Endpoint N/A (Used within an Express app) #### Parameters None #### Request Body N/A #### Request Example ```javascript import express from 'express'; import { trackRequestResponseTime } from 'system-monitoring'; const app = express(); app.use(trackRequestResponseTime()); app.get('/', (req, res) => { res.send('Response time tracked.'); }); app.listen(3000, () => { console.log('Server is running on port 3000'); }); ``` #### Response ##### Success Response (200) - **`X-Response-Time`** (header) - The response time in milliseconds. ### `createErrorTrackingMiddleware()` #### Description Factory function to create a middleware that tracks error rates. Error information is available via `req.errorResponse`. #### Method `USE` (Express middleware) #### Endpoint N/A (Used within an Express app) #### Parameters None #### Request Body N/A #### Request Example ```javascript import express from 'express'; import { createErrorTrackingMiddleware } from 'system-monitoring'; const app = express(); const errorTrackingMiddleware = createErrorTrackingMiddleware(); app.use(errorTrackingMiddleware); app.get('/error', (req, res) => { // Access error tracking info via req.errorResponse console.log(req.errorResponse); res.status(500).send('An error occurred.'); }); app.listen(3000, () => { console.log('Server is running on port 3000'); }); ``` #### Response ##### Success Response (200) - **`req.errorResponse`** (object) - An object containing error tracking information. ``` -------------------------------- ### System Monitoring Functions Source: https://www.npmjs.com/package/system-monitoring/index_activeTab=dependents Provides various functions to retrieve system performance metrics. ```APIDOC ## System Monitoring Functions ### getCpuInfo() Returns CPU usage details for all cores and the system as a whole. ### getMemoryUsage() Retrieves total, free, and used memory information. ### getDiskUsage() Fetches disk usage statistics including total, used, and available space. ### getNetworkInfo() Returns details about all network interfaces. ### getSystemUptime() Returns the system uptime in seconds. ### getProcessInfo() Provides the CPU and memory usage of the current process. ### getOSInfo Retrieves detailed information about the operating system. ### getLoadAverage Retrieves the system load averages over 1, 5, and 15 minutes. ### getUserInfo Retrieves extended user information and system details. ### getTemperature() Returns the system temperature (if supported). ### getFileSystemInfo Retrieves information about the file system, including disk space usage. ### getActiveConnections Retrieves the active network connections on the system. ### getScheduledTasks Retrieves a list of scheduled tasks from the system and parses them into an object. ### getServiceStatus Retrieves the status of a given service. ### getLogs(path, keyword) Fetches logs from the specified file, optionally filtering by a keyword. #### Parameters * **path** (string) - Required - The path to the log file. * **keyword** (string) - Optional - A keyword to filter the logs by. ```