MemoryInspector 1.0.0
dotnet add package MemoryInspector --version 1.0.0
NuGet\Install-Package MemoryInspector -Version 1.0.0
<PackageReference Include="MemoryInspector" Version="1.0.0" />
<PackageVersion Include="MemoryInspector" Version="1.0.0" />
<PackageReference Include="MemoryInspector" />
paket add MemoryInspector --version 1.0.0
#r "nuget: MemoryInspector, 1.0.0"
#:package MemoryInspector@1.0.0
#addin nuget:?package=MemoryInspector&version=1.0.0
#tool nuget:?package=MemoryInspector&version=1.0.0
MemoryInspector
๐ Memory monitoring and diagnostics for ASP.NET Core applications
๐ Exposes /memoryz
endpoint with heap usage, GC info, loaded assemblies, and thread count
โก Real-time memory insights for performance monitoring and debugging
๐ Features
โ
Heap Usage Monitoring - Track Gen 0, Gen 1, Gen 2, and Large Object Heap
๐ง GC Information - Garbage collection statistics and settings
๐ฆ Assembly Tracking - List all loaded assemblies with sizes
๐งต Thread Monitoring - Thread count and thread pool information
๐ป System Metrics - CPU usage, memory usage, and system information
๐ง Easy Integration - Simple extension methods for ASP.NET Core
๐ฆ Installation
dotnet add package MemoryInspector
๐ฏ Quick Start
Basic Usage
using MemoryInspector;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseRouting();
// Add memory inspector endpoint
app.MapEndpoints(endpoints =>
{
endpoints.MapMemoryInspector();
});
app.Run();
Detailed Endpoints
app.MapEndpoints(endpoints =>
{
endpoints.MapDetailedMemoryInspector();
});
This creates multiple endpoints:
GET /memoryz
- Complete memory informationGET /memoryz/process
- Process-specific informationGET /memoryz/heap
- Heap memory detailsGET /memoryz/gc
- Garbage collection statisticsGET /memoryz/assemblies
- Loaded assemblies listGET /memoryz/threads
- Thread informationGET /memoryz/system
- System metricsGET /memoryz/formatted
- Human-readable memory usagePOST /memoryz/force-gc
- Force garbage collection
๐ Usage Examples
1. Basic Memory Inspector
app.MapEndpoints(endpoints =>
{
endpoints.MapMemoryInspector("/memoryz");
});
2. Custom Path
app.MapEndpoints(endpoints =>
{
endpoints.MapMemoryInspector("/api/memory");
});
3. Simple Memory Usage
app.MapEndpoints(endpoints =>
{
endpoints.MapSimpleMemoryInspector("/memoryz");
});
4. Custom Inspector
var customInspector = new MemoryInspectorService();
app.MapEndpoints(endpoints =>
{
endpoints.MapMemoryInspector(customInspector, "/memoryz");
});
5. Programmatic Usage
var inspector = new MemoryInspectorService();
// Get complete memory info
var memoryInfo = inspector.GetMemoryInfo();
// Get specific information
var processInfo = inspector.GetProcessInfo();
var heapInfo = inspector.GetHeapInfo();
var gcInfo = inspector.GetGCInfo();
// Force garbage collection
inspector.ForceGC();
// Get formatted memory usage
var formatted = inspector.GetFormattedMemoryUsage();
๐ API Response Examples
Complete Memory Information
{
"timestamp": "2024-01-15T10:30:00.000Z",
"process": {
"processId": 12345,
"processName": "MyApp",
"startTime": "2024-01-15T09:00:00.000Z",
"totalProcessorTime": "00:01:30.5000000",
"userProcessorTime": "00:01:25.2000000",
"workingSet": 52428800,
"privateMemorySize": 41943040,
"virtualMemorySize": 1073741824
},
"heap": {
"totalAllocated": 16777216,
"totalReserved": 33554432,
"gen0HeapSize": 4194304,
"gen1HeapSize": 8388608,
"gen2HeapSize": 16777216,
"largeObjectHeapSize": 4194304,
"memoryLoad": 65.5
},
"garbageCollection": {
"totalCollections": 15,
"gen0Collections": 10,
"gen1Collections": 3,
"gen2Collections": 2,
"isServerGC": false,
"gcLatencyMode": "Interactive",
"lastGCTime": 0
},
"assemblies": {
"totalAssemblies": 45,
"assemblies": [
{
"name": "System.Private.CoreLib",
"version": "8.0.0.0",
"location": "C:\\Program Files\\dotnet\\shared\\Microsoft.NETCore.App\\8.0.0\\System.Private.CoreLib.dll",
"size": 12345678
}
]
},
"threads": {
"totalThreads": 12,
"activeThreads": 8,
"backgroundThreads": 4,
"foregroundThreads": 8,
"threadPool": {
"availableWorkerThreads": 32767,
"availableCompletionPortThreads": 1000,
"maxWorkerThreads": 32767,
"maxCompletionPortThreads": 1000
}
},
"system": {
"totalPhysicalMemory": 17179869184,
"availablePhysicalMemory": 8589934592,
"totalVirtualMemory": 34359738368,
"availableVirtualMemory": 17179869184,
"cpuUsage": 25.5,
"memoryUsage": 50.0
}
}
Simple Memory Usage
{
"timestamp": "2024-01-15T10:30:00.000Z",
"workingSet": 52428800,
"privateMemory": 41943040,
"totalAllocated": 16777216,
"gen0Size": 4194304,
"gen1Size": 8388608,
"gen2Size": 16777216,
"lohSize": 4194304,
"threadCount": 12,
"assemblyCount": 45,
"cpuUsage": 25.5,
"memoryUsage": 50.0
}
๐ API Reference
Extension Methods
Method | Description |
---|---|
MapMemoryInspector(string path = "/memoryz") |
Maps basic memory inspector endpoint |
MapMemoryInspector(IMemoryInspector inspector, string path = "/memoryz") |
Maps memory inspector with custom inspector |
MapDetailedMemoryInspector(string basePath = "/memoryz") |
Maps detailed memory endpoints |
MapSimpleMemoryInspector(string path = "/memoryz") |
Maps simple memory usage endpoint |
MapMemoryInspectorWithPath(string path) |
Maps memory inspector with custom path |
MapMemoryInspectorWithPath(IMemoryInspector inspector, string path) |
Maps memory inspector with custom inspector and path |
IMemoryInspector Interface
Method | Description |
---|---|
GetMemoryInfo() |
Gets comprehensive memory information |
GetProcessInfo() |
Gets process-specific information |
GetHeapInfo() |
Gets heap memory information |
GetGCInfo() |
Gets garbage collection information |
GetAssembliesInfo() |
Gets loaded assemblies information |
GetThreadInfo() |
Gets thread information |
GetSystemInfo() |
Gets system information |
ForceGC() |
Forces garbage collection |
GetFormattedMemoryUsage() |
Gets formatted memory usage string |
๐จ Advanced Examples
Custom Memory Inspector
public class CustomMemoryInspector : IMemoryInspector
{
private readonly IMemoryInspector _baseInspector;
public CustomMemoryInspector()
{
_baseInspector = new MemoryInspectorService();
}
public MemoryInfo GetMemoryInfo()
{
var info = _baseInspector.GetMemoryInfo();
// Add custom metrics
var customInfo = new MemoryInfo
{
Timestamp = info.Timestamp,
Process = info.Process,
Heap = info.Heap,
GarbageCollection = info.GarbageCollection,
Assemblies = info.Assemblies,
Threads = info.Threads,
System = info.System
};
return customInfo;
}
// Implement other interface methods...
}
// Usage
var customInspector = new CustomMemoryInspector();
app.MapEndpoints(endpoints =>
{
endpoints.MapMemoryInspector(customInspector, "/memoryz");
});
Memory Monitoring Middleware
public class MemoryMonitoringMiddleware
{
private readonly RequestDelegate _next;
private readonly IMemoryInspector _inspector;
public MemoryMonitoringMiddleware(RequestDelegate next)
{
_next = next;
_inspector = new MemoryInspectorService();
}
public async Task InvokeAsync(HttpContext context)
{
var startMemory = _inspector.GetMemoryInfo();
await _next(context);
var endMemory = _inspector.GetMemoryInfo();
var memoryDiff = endMemory.Heap.TotalAllocated - startMemory.Heap.TotalAllocated;
if (memoryDiff > 1024 * 1024) // 1MB threshold
{
Console.WriteLine($"Memory increase: {memoryDiff} bytes");
}
}
}
// Usage
app.UseMiddleware<MemoryMonitoringMiddleware>();
Health Check Integration
builder.Services.AddHealthChecks()
.AddCheck<MemoryHealthCheck>("memory");
public class MemoryHealthCheck : IHealthCheck
{
private readonly IMemoryInspector _inspector;
public MemoryHealthCheck()
{
_inspector = new MemoryInspectorService();
}
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
var memoryInfo = _inspector.GetMemoryInfo();
var memoryUsage = memoryInfo.System.MemoryUsage;
if (memoryUsage > 90)
{
return Task.FromResult(HealthCheckResult.Unhealthy($"High memory usage: {memoryUsage:F1}%"));
}
if (memoryUsage > 80)
{
return Task.FromResult(HealthCheckResult.Degraded($"Elevated memory usage: {memoryUsage:F1}%"));
}
return Task.FromResult(HealthCheckResult.Healthy($"Memory usage: {memoryUsage:F1}%"));
}
}
๐งช Testing Examples
Unit Testing
[Test]
public void GetMemoryInfo_ReturnsValidData()
{
// Arrange
var inspector = new MemoryInspectorService();
// Act
var memoryInfo = inspector.GetMemoryInfo();
// Assert
Assert.That(memoryInfo.Timestamp, Is.GreaterThan(DateTime.UtcNow.AddMinutes(-1)));
Assert.That(memoryInfo.Process.ProcessId, Is.GreaterThan(0));
Assert.That(memoryInfo.Heap.TotalAllocated, Is.GreaterThan(0));
Assert.That(memoryInfo.Assemblies.TotalAssemblies, Is.GreaterThan(0));
Assert.That(memoryInfo.Threads.TotalThreads, Is.GreaterThan(0));
}
Integration Testing
[Test]
public async Task MemoryInspectorEndpoint_ReturnsValidJson()
{
// Arrange
var builder = WebApplication.CreateBuilder();
var app = builder.Build();
app.MapEndpoints(endpoints =>
{
endpoints.MapMemoryInspector("/test-memory");
});
var client = app.CreateClient();
// Act
var response = await client.GetAsync("/test-memory");
var content = await response.Content.ReadAsStringAsync();
// Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
Assert.That(content, Is.Not.Empty);
var memoryInfo = JsonSerializer.Deserialize<MemoryInfo>(content);
Assert.That(memoryInfo, Is.Not.Null);
Assert.That(memoryInfo.Process.ProcessId, Is.GreaterThan(0));
}
๐ง Configuration
The package works out of the box with sensible defaults. No configuration required!
Optional: Custom Inspector
// Create a custom inspector for advanced scenarios
var customInspector = new MemoryInspectorService();
// Use the custom inspector in your endpoints
app.MapEndpoints(endpoints =>
{
endpoints.MapMemoryInspector(customInspector, "/memoryz");
});
๐ค Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Submit a pull request
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Support
- ๐ง Email: asajjad308@gmail.com
๐ Roadmap
- Memory leak detection
- Historical memory tracking
- Memory profiling integration
- Custom metrics support
- Alerting and notifications
- Memory dump generation
- Performance counters integration
- Memory optimization suggestions
- Real-time memory monitoring
- Memory usage trends analysis
Made with โค๏ธ for the .NET community
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. 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. |
-
net8.0
- Microsoft.AspNetCore.Http.Abstractions (>= 2.2.0)
- Microsoft.AspNetCore.Routing.Abstractions (>= 2.2.0)
- System.Diagnostics.PerformanceCounter (>= 8.0.0)
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.0.0 | 150 | 8/4/2025 |