Resource monitoring involves the continuous measurement of resource utilization over a specified period. The Microsoft.Extensions.Diagnostics.ResourceMonitoring NuGet package offers a collection of APIs tailored for monitoring the resource utilization of your .NET applications.
The IResourceMonitor interface furnishes methods for retrieving real-time information concerning process resource utilization. This interface supports the retrieval of data related to CPU and memory usage and is currently compatible with both Windows and Linux platforms. All resource monitoring diagnostic information is published to OpenTelemetry by default, so there's no need to manually publish this yourself.
The following example demonstrates how to use the IResourceMonitor interface to retrieve information about the current process's CPU and memory usage.
C#
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.ResourceMonitoring;
using Microsoft.Extensions.Logging;
using Spectre.Console;
var services = new ServiceCollection()
.AddLogging(static builder => builder.AddConsole())
.AddResourceMonitoring();
var provider = services.BuildServiceProvider();
var monitor = provider.GetRequiredService<IResourceMonitor>();
Builds a new ServiceProvider instance from the ServiceCollection instance.
Gets an instance of the IResourceMonitor interface from the ServiceProvider instance.
Important
The Microsoft.Extensions.Diagnostics.ResourceMonitoring package assumes that the consumer will register logging providers with the Microsoft.Extensions.Logging package. If you don't register logging, the call to AddResourceMonitoring will throw an exception. Furthermore, you can enable internal library logging by configuring the Debug log level for the Microsoft.Extensions.Diagnostics.ResourceMonitoring category as per the guide.
At this point, with the IResourceMonitor implementation you'll ask for resource utilization with the IResourceMonitor.GetUtilization method. The GetUtilization method returns a ResourceUtilization instance that contains the following information:
Extending this example, you can leverage Spectre.Console, a well-regarded .NET library designed to simplify the development of visually appealing, cross-platform console applications. With Spectre, you'll be able to present resource utilization data in a tabular format. The following code illustrates the usage of the IResourceMonitor interface to access details regarding the CPU and memory usage of the current process, then presenting this data in a table:
C#
await StartMonitoringAsync(monitor, token);
async Task StartMonitoringAsync(IResourceMonitor monitor, CancellationToken cancellationToken)
{
var table = new Table()
.Centered()
.Title("Resource Monitoring", new Style(foreground: Color.Purple, decoration: Decoration.Bold))
.Caption("Updates every three seconds. *GTD: Guaranteed ", new Style(decoration: Decoration.Dim))
.RoundedBorder()
.BorderColor(Color.Cyan1)
.AddColumns(
[
new TableColumn("Time").Centered(),
new TableColumn("CPU %").Centered(),
new TableColumn("Memory %").Centered(),
new TableColumn("Memory (bytes)").Centered(),
new TableColumn("GTD / Max Memory (bytes)").Centered(),
new TableColumn("GTD / Max CPU (units)").Centered(),
]);
await AnsiConsole.Live(table)
.StartAsync(async ctx =>
{
var window = TimeSpan.FromSeconds(3);
while (cancellationToken.IsCancellationRequested isfalse)
{var utilization = monitor.GetUtilization(window);
var resources = utilization.SystemResources;
table.AddRow(
[$"{DateTime.Now:T}",$"{utilization.CpuUsedPercentage:p}",
$"{utilization.MemoryUsedPercentage:p}",
$"{utilization.MemoryUsedInBytes:#,#}",
$"{resources.GuaranteedMemoryInBytes:#,#} / {resources.MaximumMemoryInBytes:#,#}",
$"{resources.GuaranteedCpuUnits} / {resources.MaximumCpuUnits}",]);
ctx.Refresh();
await Task.Delay(window);
}
});
Console.CancelKeyPress += (_, e) =>
{
e.Cancel = true;
cancellationTokenSource.Cancel();
};
}
The preceding code:
Creates a cancellation token source and a cancellation token.
Creates a new Table instance, configuring it with a title, caption, and columns.
Performs a live render of the Table instance, passing in a delegate that will be invoked every three seconds.
Gets the current resource utilization information from the IResourceMonitor instance and displays it as a new row in the Table instance.
The following is an example of the output from the preceding code:
In addition to resource monitoring, apps that exist within a Kubernetes cluster report their health through diagnostic probes. The Microsoft.Extensions.Diagnostics.Probes NuGet package provides support for Kubernetes probes. It externalizes various health checks that align with various Kubernetes probes, for example:
Liveness
Readiness
Startup
The library communicates the apps current health to a Kubernetes hosting environment. If a process reports as being unhealthy, Kubernetes doesn't send it any traffic, providing the process time to recover or terminate.
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, see our contributor guide.
.NET feedback
.NET is an open source project. Select a link to provide feedback:
Learn about observability and how to implement it in a cloud-native application. Use OpenTelemetry packages to output logs, metrics, and tracing data and analyze the data in Application Insights and third-party applications.