Skip to content

Instantly share code, notes, and snippets.

@pedroinfo
Last active December 9, 2025 19:45
Show Gist options
  • Select an option

  • Save pedroinfo/9f769046bf407d4da4806913f692a26e to your computer and use it in GitHub Desktop.

Select an option

Save pedroinfo/9f769046bf407d4da4806913f692a26e to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Diagnostics;
public static class SystemInfoHelper
{
// Stores last CPU and time samples to compute deltas
private static TimeSpan _lastCpu = TimeSpan.Zero;
private static DateTime _lastSampleTime = DateTime.UtcNow;
/// <summary>
/// Returns the CPU usage percentage of the current IIS worker process (w3wp).
/// This method does NOT require PerformanceCounter or registry access.
/// </summary>
public static double GetCpuUsage()
{
var process = Process.GetCurrentProcess();
var now = DateTime.UtcNow;
var currentCpu = process.TotalProcessorTime;
var cpuUsedMs = (currentCpu - _lastCpu).TotalMilliseconds;
var elapsedMs = (now - _lastSampleTime).TotalMilliseconds;
// Update deltas
_lastCpu = currentCpu;
_lastSampleTime = now;
if (elapsedMs <= 0)
return 0;
// CPU percentage normalized by number of logical processors
var cpuPercent = cpuUsedMs / (elapsedMs * Environment.ProcessorCount);
// Clamp between 0–100%
cpuPercent = Math.Max(0, Math.Min(cpuPercent, 1));
return Math.Round(cpuPercent * 100, 2);
}
/// <summary>
/// Returns the memory usage (Working Set) of the current IIS worker process in MB.
/// </summary>
public static double GetMemoryUsageMB()
{
var bytes = Process.GetCurrentProcess().WorkingSet64;
return Math.Round(bytes / 1024.0 / 1024.0, 2);
}
/// <summary>
/// Returns readable uptime text (e.g. "2 days, 3 hours, 12 minutes").
/// </summary>
public static string GetReadableUptime()
{
var process = Process.GetCurrentProcess();
var uptime = DateTime.UtcNow - process.StartTime.ToUniversalTime();
return TimeSpanToReadableString(uptime);
}
/// <summary>
/// Converts a TimeSpan to a friendly human-readable string.
/// </summary>
private static string TimeSpanToReadableString(TimeSpan ts)
{
var parts = new List<string>();
if (ts.Days > 0)
parts.Add($"{ts.Days} day{(ts.Days > 1 ? "s" : "")}");
if (ts.Hours > 0)
parts.Add($"{ts.Hours} hour{(ts.Hours > 1 ? "s" : "")}");
if (ts.Minutes > 0)
parts.Add($"{ts.Minutes} minute{(ts.Minutes > 1 ? "s" : "")}");
if (ts.Seconds > 0)
parts.Add($"{ts.Seconds} second{(ts.Seconds > 1 ? "s" : "")}");
if (parts.Count == 0)
return "0 seconds";
return string.Join(", ", parts);
}
}
@pedroinfo
Copy link
Author

var metrics = new
{
Cpu = SystemHealthHelper.GetCpuUsage(),
Memory = SystemHealthHelper.GetMemoryUsageBytes(),
Version = SystemHealthHelper.GetAppVersion(),
AppName = SystemHealthHelper.GetAppName(),
Uptime = SystemHealthHelper.GetUptime(),
Timestamp = DateTime.UtcNow
};

LogService.LogHeartbeat(metrics);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment