ModMon.Modules.HostMetrics 1.2.0

dotnet add package ModMon.Modules.HostMetrics --version 1.2.0
                    
NuGet\Install-Package ModMon.Modules.HostMetrics -Version 1.2.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="ModMon.Modules.HostMetrics" Version="1.2.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="ModMon.Modules.HostMetrics" Version="1.2.0" />
                    
Directory.Packages.props
<PackageReference Include="ModMon.Modules.HostMetrics" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add ModMon.Modules.HostMetrics --version 1.2.0
                    
#r "nuget: ModMon.Modules.HostMetrics, 1.2.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package ModMon.Modules.HostMetrics@1.2.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=ModMon.Modules.HostMetrics&version=1.2.0
                    
Install as a Cake Addin
#tool nuget:?package=ModMon.Modules.HostMetrics&version=1.2.0
                    
Install as a Cake Tool

ModMon.HostMetrics

Comprehensive host system metrics monitoring module for the ModMon framework. Provides real-time collection and analysis of CPU, memory, disk, network, and process metrics with configurable alerts, health checks, and background processing.

Features

🖥️ Comprehensive Metrics Collection

  • CPU Metrics: Usage percentage, load averages, processor count, process CPU time
  • Memory Metrics: Physical memory usage, process working set, managed memory, virtual memory
  • Disk Metrics: Space utilization, I/O operations, read/write rates for all drives
  • Network Metrics: Bandwidth usage, active connections, interface statistics
  • Process Metrics: Thread count, handle count, uptime, peak memory usage
  • Garbage Collection: Collection counts, heap size, GC pressure analysis
  • Thread Pool: Worker threads, completion port threads, queue statistics

📊 Rich API Endpoints

  • /api/host-metrics/current - Get current system metrics
  • /api/host-metrics/history - Historical metrics with time range filtering
  • /api/host-metrics/system-info - Static system information
  • /api/host-metrics/performance - Performance summary and health indicators
  • /api/host-metrics/health - Module health status
  • /api/host-metrics/config - Current configuration
  • /api/host-metrics/collect - Manual metrics collection trigger

🔄 Background Processing

  • Automatic Collection: Configurable interval-based metrics gathering
  • Data Retention: Automatic cleanup of old metrics based on retention policies
  • Manual Tasks: On-demand collection and cleanup operations
  • Retry Logic: Robust error handling with configurable retry mechanisms

🏥 Health Monitoring

  • Integrated Health Checks: ASP.NET Core health check integration
  • Performance Alerts: Configurable thresholds for critical metrics
  • Status Reporting: Detailed health status with diagnostic information
  • Failure Tracking: Consecutive failure monitoring and alerting

⚙️ Flexible Configuration

  • Granular Control: Enable/disable individual metric types
  • Performance Tuning: Configurable collection intervals and timeouts
  • Storage Options: In-memory caching with size limits and retention policies
  • Alert Thresholds: Customizable warning and critical thresholds

Installation

dotnet add package ModMon.HostMetrics

Quick Start

1. Register the Module

using ModMon.Hosting;
using ModMon.HostMetrics;

var app = ModMonApplication.CreateBuilder(args)
    .AddModuleDefaults()
    .AddModule<HostMetricsModule>()
    .Build();

app.Run();

2. Configure Options (Optional)

Add to your appsettings.json:

{
  "Modules": {
    "HostMetrics": {
      "Collection": {
        "EnableCollection": true,
        "EnableBackgroundCollection": true,
        "CollectionInterval": "00:01:00"
      },
      "Storage": {
        "EnableInMemoryCache": true,
        "MaxCacheSize": 1440,
        "RetentionPeriod": "7.00:00:00"
      },
      "Alerts": {
        "CpuUsageThreshold": 80.0,
        "MemoryUsageThreshold": 85.0,
        "DiskUsageThreshold": 90.0
      }
    }
  }
}

3. Use the API

# Get current metrics
curl http://localhost:5000/api/host-metrics/current

# Get historical data
curl "http://localhost:5000/api/host-metrics/history?from=2025-01-01T00:00:00Z&to=2025-01-01T23:59:59Z&intervalMinutes=5"

# Check health
curl http://localhost:5000/api/host-metrics/health

Configuration Options

Collection Settings

{
  "Collection": {
    "EnableCollection": true,
    "EnableBackgroundCollection": true,
    "CollectionInterval": "00:01:00",
    "CollectionTimeout": "00:00:30",
    "EnableCpuMetrics": true,
    "EnableMemoryMetrics": true,
    "EnableDiskMetrics": true,
    "EnableNetworkMetrics": true,
    "EnableProcessMetrics": true,
    "EnableGcMetrics": true,
    "EnableThreadPoolMetrics": true,
    "MonitoredDrives": [],
    "MonitoredNetworkInterfaces": [],
    "MaxRetries": 3,
    "RetryDelay": "00:00:05"
  }
}

Storage Settings

{
  "Storage": {
    "EnableInMemoryCache": true,
    "MaxCacheSize": 1440,
    "RetentionPeriod": "7.00:00:00",
    "EnableAutoCleanup": true,
    "CleanupInterval": "1.00:00:00",
    "EnableCompression": false
  }
}

Alert Thresholds

{
  "Alerts": {
    "EnableAlerts": true,
    "CpuUsageThreshold": 80.0,
    "MemoryUsageThreshold": 85.0,
    "DiskUsageThreshold": 90.0,
    "NetworkUsageThreshold": 104857600,
    "GcPressureThreshold": 10.0,
    "ThreadCountThreshold": 200,
    "CustomThresholds": {},
    "AlertCooldown": "00:05:00"
  }
}

Performance Analysis

{
  "Performance": {
    "EnablePerformanceAnalysis": true,
    "AnalysisWindowSize": 60,
    "EnableRecommendations": true,
    "EnableTrendAnalysis": true,
    "MinTrendDataPoints": 10,
    "EnableAnomalyDetection": false,
    "AnomalyThreshold": 2.0
  }
}

API Examples

Get Current Metrics

Request:

GET /api/host-metrics/current

Response:

{
  "timestamp": "2025-08-22T16:30:00Z",
  "machineName": "web-server-01",
  "cpu": {
    "usagePercent": 45.2,
    "logicalProcessors": 8,
    "loadAverages": [1.2, 1.5, 1.8],
    "processCpuTime": "01:23:45",
    "systemUptime": "5.12:34:56"
  },
  "memory": {
    "totalBytes": 17179869184,
    "availableBytes": 8589934592,
    "usedBytes": 8589934592,
    "usagePercent": 50.0,
    "processWorkingSet": 134217728,
    "processPrivateMemory": 268435456,
    "managedMemory": 67108864,
    "virtualMemoryUsage": 536870912
  },
  "disks": [
    {
      "driveName": "C:",
      "fileSystem": "NTFS",
      "totalBytes": 1099511627776,
      "freeBytes": 549755813888,
      "usedBytes": 549755813888,
      "usagePercent": 50.0,
      "readOpsPerSecond": 15.2,
      "writeOpsPerSecond": 8.7,
      "readBytesPerSecond": 1048576,
      "writeBytesPerSecond": 524288
    }
  ],
  "network": {
    "bytesReceivedPerSecond": 1048576,
    "bytesSentPerSecond": 524288,
    "totalBytesReceived": 1099511627776,
    "totalBytesSent": 549755813888,
    "activeConnections": 42,
    "interfaces": [
      {
        "name": "Ethernet",
        "description": "Intel Ethernet Controller",
        "isUp": true,
        "bytesReceived": 1099511627776,
        "bytesSent": 549755813888,
        "speed": 1000000000
      }
    ]
  },
  "process": {
    "processId": 1234,
    "processName": "MyApp",
    "startTime": "2025-08-22T12:00:00Z",
    "uptime": "04:30:00",
    "threadCount": 15,
    "handleCount": 456,
    "peakWorkingSet": 268435456,
    "peakVirtualMemory": 1073741824
  },
  "garbageCollection": {
    "totalCollections": 1250,
    "collectionsByGeneration": [800, 350, 100],
    "totalAllocatedBytes": 5368709120,
    "heapSizeBytes": 134217728,
    "timeInGcPercent": 2.5,
    "largeObjectHeapSize": 16777216
  },
  "threadPool": {
    "workerThreads": 12,
    "completionPortThreads": 4,
    "maxWorkerThreads": 32,
    "maxCompletionPortThreads": 32,
    "queuedWorkItems": 3,
    "completedWorkItems": 98765
  },
  "customMetrics": {}
}

Get Performance Summary

Request:

GET /api/host-metrics/performance

Response:

{
  "generatedAt": "2025-08-22T16:30:00Z",
  "overallStatus": "Good",
  "indicators": [
    {
      "name": "CPU Usage",
      "value": 45.2,
      "unit": "%",
      "status": "Good",
      "description": "Current CPU utilization percentage",
      "threshold": 80.0
    },
    {
      "name": "Memory Usage",
      "value": 50.0,
      "unit": "%",
      "status": "Good",
      "description": "Current memory utilization percentage",
      "threshold": 85.0
    }
  ],
  "alerts": [],
  "keyMetrics": {
    "CpuUsage": 45.2,
    "MemoryUsage": 50.0,
    "ProcessWorkingSet": 128.0,
    "ThreadCount": 15,
    "HandleCount": 456,
    "GcCollections": 1250,
    "GcHeapSize": 128.0,
    "ActiveConnections": 42,
    "ProcessUptime": 4.5
  },
  "recommendations": []
}

Background Tasks

The module automatically registers background tasks:

  • HostMetricsCollectionTask: Runs every minute (configurable) to collect metrics
  • HostMetricsCleanupTask: Runs daily at 2 AM to clean up old data
  • ManualHostMetricsCollectionTask: On-demand collection for testing
  • ManualHostMetricsCleanupTask: On-demand cleanup

Monitor task execution through the ModMon background task system.

Health Checks

The module registers with ASP.NET Core health checks:

# Check overall application health (includes HostMetrics)
curl http://localhost:5000/health

# Check detailed health with HostMetrics info
curl http://localhost:5000/health/detailed

Health check validates:

  • Metrics collector functionality
  • Cache health and data freshness
  • Service health and error rates
  • Performance thresholds
  • Configuration validity

Platform Support

  • Windows: Full support with performance counters
  • Linux: Core metrics with /proc filesystem integration
  • macOS: Basic metrics support

Performance Considerations

Memory Usage

  • Default cache size: 1440 metrics (24 hours at 1-minute intervals)
  • Estimated memory: ~3MB for default cache size
  • Configurable retention and cleanup

CPU Impact

  • Collection overhead: <1% CPU on typical systems
  • Configurable collection intervals (default: 1 minute)
  • Async collection with timeouts

Disk I/O

  • In-memory caching reduces I/O
  • Optional compression for storage
  • Configurable cleanup intervals

Troubleshooting

Common Issues

Metrics not collecting:

# Check module configuration
curl http://localhost:5000/api/host-metrics/config

# Check health status
curl http://localhost:5000/api/host-metrics/health

# Check logs for errors

High memory usage:

{
  "Storage": {
    "MaxCacheSize": 720,  // Reduce cache size
    "RetentionPeriod": "3.00:00:00"  // Reduce retention
  }
}

Performance impact:

{
  "Collection": {
    "CollectionInterval": "00:05:00",  // Collect less frequently
    "EnableNetworkMetrics": false,     // Disable expensive metrics
    "EnableDiskMetrics": false
  }
}

Logging

Enable detailed logging:

{
  "Logging": {
    "LogLevel": {
      "ModMon.HostMetrics": "Debug"
    }
  }
}

Contributing

This module follows ModMon framework patterns:

  1. Interfaces: Define contracts in Contracts folder
  2. Models: Data structures in Models folder
  3. Implementation: Core logic in Implementation folder
  4. Options: Configuration in Options folder
  5. Tasks: Background tasks in Tasks folder

License

MIT License - see the LICENSE file for details.

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.2.0 174 8/29/2025
1.1.0 176 8/27/2025
1.0.4 167 8/30/2025
1.0.3 166 8/30/2025
1.0.2 150 8/25/2025
1.0.1 178 8/30/2025
1.0.0 169 8/30/2025