Skip to content

Update Resource Monitoring with using metrics #47270

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 78 additions & 10 deletions docs/core/diagnostics/diagnostic-resource-monitoring.md
Original file line number Diff line number Diff line change
@@ -1,18 +1,57 @@
---
title: Diagnostic resource monitoring
description: Learn how to use the diagnostic resource monitoring library in .NET.
ms.date: 11/29/2023
ms.date: 07/09/2025
---

# Resource monitoring

Resource monitoring involves the continuous measurement of resource utilization over a specified period. The [Microsoft.Extensions.Diagnostics.ResourceMonitoring](https://www.nuget.org/packages/Microsoft.Extensions.Diagnostics.ResourceMonitoring) NuGet package offers a collection of APIs tailored for monitoring the resource utilization of your .NET applications.
Resource monitoring involves the continuous measurement of resource utilization values, such as CPU, memory, and network usage. The [Microsoft.Extensions.Diagnostics.ResourceMonitoring](https://www.nuget.org/packages/Microsoft.Extensions.Diagnostics.ResourceMonitoring) NuGet package offers a collection of APIs tailored for monitoring the resource utilization of your .NET applications.

The <xref:Microsoft.Extensions.Diagnostics.ResourceMonitoring.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 measurements can be consumed in two ways:

In addition, the resource monitoring library reports various diagnostic metrics. For more information, see [Diagnostic Metrics: `Microsoft.Extensions.Diagnostics.ResourceMonitoring`](built-in-metrics-diagnostics.md#microsoftextensionsdiagnosticsresourcemonitoring).
- Use [.NET metrics](metrics.md).
- Use the <xref:Microsoft.Extensions.Diagnostics.ResourceMonitoring.IResourceMonitor> interface. This interface is deprecated, use the metrics-based approach instead. If you still need to listen to metric values manually, see [Migrate to metrics-based resource monitoring](#migrate-to-metrics-based-resource-monitoring).

## Example resource monitoring usage
> [!IMPORTANT]
> The <xref:Microsoft.Extensions.Diagnostics.ResourceMonitoring?displayProperty=fullName> 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`](xref:Microsoft.Extensions.Logging.LogLevel.Debug) log level for the `Microsoft.Extensions.Diagnostics.ResourceMonitoring` category as per the [guide](../extensions/logging.md#log-category).

## Use .NET metrics of resource monitoring

To consume .NET metrics produced by the Resource monitoring library:

1. Add the `Microsoft.Extensions.Diagnostics.ResourceMonitoring` package to your project.
1. Add the resource monitoring services to your dependency injection container:

```csharp
services.AddResourceMonitoring();
```

1. Configure metrics collection using any OpenTelemetry-compatible metrics collector. For example:

```csharp
services.AddOpenTelemetry()
.WithMetrics(builder =>
{
builder.AddMeter("Microsoft.Extensions.Diagnostics.ResourceMonitoring");
builder.AddConsoleExporter(); // Or any other metrics exporter
});
```

1. Now you can observe the resource usage metrics through your configured metrics exporter.

For information about available metrics, see [.NET extensions metrics: Microsoft.Extensions.Diagnostics.ResourceMonitoring](built-in-metrics-diagnostics.md#microsoftextensionsdiagnosticsresourcemonitoring).

For information about metrics collection, see [Metrics collection](metrics-collection.md).

## Use the `IResourceMonitor` interface

> [!CAUTION]
> The <xref:Microsoft.Extensions.Diagnostics.ResourceMonitoring.IResourceMonitor> interface described in this section is deprecated and might be removed in future versions of .NET. [Migrate to the metrics-based approach](#migrate-to-metrics-based-resource-monitoring).

The <xref:Microsoft.Extensions.Diagnostics.ResourceMonitoring.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.

### Example resource monitoring usage

The following example demonstrates how to use the `IResourceMonitor` interface to retrieve information about the current process's CPU and memory usage.

Expand All @@ -24,9 +63,6 @@ The preceding code:
- Builds a new <xref:Microsoft.Extensions.DependencyInjection.ServiceProvider> instance from the `ServiceCollection` instance.
- Gets an instance of the <xref:Microsoft.Extensions.Diagnostics.ResourceMonitoring.IResourceMonitor> interface from the `ServiceProvider` instance.

> [!IMPORTANT]
> The <xref:Microsoft.Extensions.Diagnostics.ResourceMonitoring?displayProperty=fullName> 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`](xref:Microsoft.Extensions.Logging.LogLevel.Debug) log level for the `Microsoft.Extensions.Diagnostics.ResourceMonitoring` category as per the [guide](../extensions/logging.md#log-category).

At this point, with the `IResourceMonitor` implementation you'll ask for resource utilization with the <xref:Microsoft.Extensions.Diagnostics.ResourceMonitoring.IResourceMonitor.GetUtilization%2A?displayProperty=nameWithType> method. The `GetUtilization` method returns a <xref:Microsoft.Extensions.Diagnostics.ResourceMonitoring.ResourceUtilization> instance that contains the following information:

- <xref:Microsoft.Extensions.Diagnostics.ResourceMonitoring.ResourceUtilization.CpuUsedPercentage?displayProperty=nameWithType>: CPU usage as a percentage.
Expand All @@ -38,7 +74,7 @@ At this point, with the `IResourceMonitor` implementation you'll ask for resourc
- <xref:Microsoft.Extensions.Diagnostics.ResourceMonitoring.SystemResources.GuaranteedCpuUnits?displayProperty=nameWithType>: Guaranteed CPU in units.
- <xref:Microsoft.Extensions.Diagnostics.ResourceMonitoring.SystemResources.MaximumCpuUnits?displayProperty=nameWithType>: Maximum CPU in units.

## Extend resource monitoring with Spectre.Console
### Extend resource monitoring with Spectre.Console

Extending this example, you can leverage [Spectre.Console](https://www.nuget.org/packages/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:

Expand All @@ -57,6 +93,37 @@ The following is an example of the output from the preceding code:

For the source code of this example, see the [Resource monitoring sample](https://github.com/dotnet/docs/tree/main/docs/core/diagnostics/snippets/resource-monitoring).

### Migrate to metrics-based resource monitoring

Since the <xref:Microsoft.Extensions.Diagnostics.ResourceMonitoring.IResourceMonitor> interface is deprecated, migrate to the metrics-based approach. The `Microsoft.Extensions.Diagnostics.ResourceMonitoring` package provides several metrics that you can use instead, for instance:

- `container.cpu.limit.utilization`: The CPU consumption share of the running containerized application relative to resource limit in range `[0, 1]`. Available for containerized apps on Linux and Windows.
- `container.cpu.request.utilization`: The CPU consumption share of the running containerized application relative to resource request in range `[0, 1]`. Available for containerized apps on Linux.
- `container.memory.limit.utilization`: The memory consumption share of the running containerized application relative to resource limit in range `[0, 1]`. Available for containerized apps on Linux and Windows.

See the [Built-in metrics: Microsoft.Extensions.Diagnostics.ResourceMonitoring](built-in-metrics-diagnostics.md#microsoftextensionsdiagnosticsresourcemonitoring) section for more information about the available metrics.

#### Migration guide

This section provides a migration guide from the deprecated `IResourceMonitor` interface to the metrics-based approach. You only need this guide if you manually listen to resource utilization metrics in your application. In most cases, you don't need to listen to metrics manually because they're automatically collected and exported to back-ends using metrics exporters, as described in [Use .NET metrics of Resource monitoring](#use-net-metrics-of-resource-monitoring).

If you have code similar to the `IResourceMonitor` [example usage](#example-resource-monitoring-usage), update it as follows:

:::code source="snippets/resource-monitoring-with-manual-metrics/Program.cs" id="monitor" :::

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 using a callback set with the `SetMeasurementEventCallback` method and displays it as a new row in the `Table` instance.

The following is an example of the output from the preceding code:

:::image type="content" source="media/resource-monitoring-with-manual-metrics-output.png" lightbox="media/resource-monitoring-with-manual-metrics-output.png" alt-text="Example Resource Monitoring with manual metrics app output.":::

For the complete source code of this example, see the [Resource monitoring with manual metrics sample](https://github.com/dotnet/docs/tree/main/docs/core/diagnostics/snippets/resource-monitoring-with-manual-metrics).

## Kubernetes probes

In addition to resource monitoring, apps that exist within a Kubernetes cluster report their health through diagnostic probes. The [Microsoft.Extensions.Diagnostics.Probes](https://www.nuget.org/packages/Microsoft.Extensions.Diagnostics.Probes) NuGet package provides support for Kubernetes probes. It externalizes various [health checks](diagnostic-health-checks.md) that align with various Kubernetes probes, for example:
Expand All @@ -65,10 +132,11 @@ In addition to resource monitoring, apps that exist within a Kubernetes cluster
- 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 library communicates the app's 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.

To add support for Kubernetes probes, add a package reference to [Microsoft.Extensions.Diagnostics.Probes](https://www.nuget.org/packages/Microsoft.Extensions.Diagnostics.Probes). On an <xref:Microsoft.Extensions.DependencyInjection.IServiceCollection> instance, call <xref:Microsoft.Extensions.DependencyInjection.KubernetesProbesExtensions.AddKubernetesProbes%2A>.

## See also

- [.NET extensions metrics](built-in-metrics-diagnostics.md)
- [Observability with OpenTelemetry](observability-with-otel.md)
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
FROM mcr.microsoft.com/dotnet/runtime:9.0 AS base
WORKDIR /app

FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
WORKDIR /src
COPY ["ResourceMonitoring/ResourceMonitoring.csproj", "ResourceMonitoring/"]
RUN dotnet restore "ResourceMonitoring/ResourceMonitoring.csproj"
COPY . .
WORKDIR "/src/ResourceMonitoring"
RUN dotnet build "ResourceMonitoring.csproj" -c Debug -o /app/build

FROM build AS publish
RUN dotnet publish "ResourceMonitoring.csproj" -c Debug -o /app/publish /p:UseAppHost=false

FROM base AS final
RUN apt-get update && apt-get install -y gdb
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "ResourceMonitoring.dll"]
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
using System.Diagnostics.Metrics;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Spectre.Console;

// <setup>
var app = Host.CreateDefaultBuilder()
.ConfigureServices(services =>
{
services.AddLogging(static builder => builder.AddConsole())
.AddResourceMonitoring();
})
.Build();

var logger = app.Services.GetRequiredService<ILogger<Program>>();
await app.StartAsync();
// </setup>

using var cancellationTokenSource = new CancellationTokenSource();
var token = cancellationTokenSource.Token;
Console.CancelKeyPress += (_, e) =>
{
e.Cancel = true;
cancellationTokenSource.Cancel();
};

// <monitor>
await StartMonitoringAsync(logger, token);

async Task StartMonitoringAsync(ILogger logger, CancellationToken cancellationToken)
{
var table = new Table()
.Centered()
.Title("Resource Monitoring", new Style(foreground: Color.Purple, decoration: Decoration.Bold))
.RoundedBorder()
.BorderColor(Color.Cyan1)
.AddColumns(
[
new TableColumn("Time").Centered(),
new TableColumn("CPU limit %").Centered(),
new TableColumn("CPU request %").Centered(),
new TableColumn("Memory limit %").Centered(),
]);

const string rmMeterName = "Microsoft.Extensions.Diagnostics.ResourceMonitoring";
using var meter = new Meter(rmMeterName);
using var meterListener = new MeterListener
{
InstrumentPublished = (instrument, listener) =>
{
if (instrument.Meter.Name == rmMeterName &&
instrument.Name.StartsWith("container."))
{
listener.EnableMeasurementEvents(instrument, null);
}
}
};

var samples = new Dictionary<string, double>();
meterListener.SetMeasurementEventCallback<double>((instrument, value, _, _) =>
{
if (instrument.Meter.Name == rmMeterName)
{
samples[instrument.Name] = value;
}
});
meterListener.Start();

await AnsiConsole.Live(table)
.StartAsync(async ctx =>
{
var window = TimeSpan.FromSeconds(5);
while (cancellationToken.IsCancellationRequested is false)
{
meterListener.RecordObservableInstruments();

table.AddRow(
[
$"{DateTime.Now:T}",
$"{samples["container.cpu.limit.utilization"]:p}",
$"{samples["container.cpu.request.utilization"]:p}",
$"{samples["container.memory.limit.utilization"]:p}",
]);

ctx.Refresh();

await Task.Delay(window);
}
});
}
// </monitor>
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"profiles": {
"Container (Dockerfile)": {
"commandName": "Docker"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.21.2" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="9.0.6" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.6" />
<PackageReference Include="Microsoft.Extensions.Diagnostics.ResourceMonitoring" Version="9.6.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.6" />
<PackageReference Include="Spectre.Console" Version="0.50.0" />
</ItemGroup>

</Project>