Level Up Your .NET 8 ASP.NET Core App: Metrics with IMeterFactory and Azure Application Insights
In the world of modern application development, observability is king. You need to know how your application is performing, and metrics are a crucial part of that. In .NET 8, IMeterFactory
provides a powerful and standardized way to instrument your code. Coupled with Azure Application Insights, you can gain deep insights into your application's behavior. Let's dive into how to set this up in your ASP.NET Core application.
1. Project Setup and Dependencies
First, create a new ASP.NET Core Web API project (or use an existing one). Then, add the necessary NuGet packages:
dotnet add package Microsoft.Extensions.Diagnostics.Abstractions
dotnet add package Microsoft.Extensions.Diagnostics.Metrics
dotnet add package Azure.Monitor.OpenTelemetry.AspNetCore
Microsoft.Extensions.Diagnostics.Abstractions
: Provides core abstractions for diagnostics.
Microsoft.Extensions.Diagnostics.Metrics
: Contains the IMeterFactory and related types.
Azure.Monitor.OpenTelemetry.AspNetCore
: Enables OpenTelemetry integration with Azure Application Insights.
2. Configuring IMeterFactory and Application Insights
Modify your Program.cs
file to configure IMeterFactory
and enable Application Insights:
using Microsoft.Extensions.Diagnostics.Metrics;
var builder = WebApplication.CreateBuilder(args);
// Add Application Insights
builder.Services.AddApplicationInsightsTelemetry();
// Add MeterFactory
builder.Services.AddMetrics();
// ... other services ...
var app = builder.Build();
// ... middleware ...
app.Run();
This snippet does the following:
builder.Services.AddApplicationInsightsTelemetry();
: Configures Application Insights with OpenTelemetry, automatically collecting telemetry data.
builder.Services.AddMetrics();
: Registers the IMeterFactory with the dependency injection container.
3. Instrumenting Your Code
Now, let's add some instrumentation to your code. For example, we'll track the number of HTTP requests:
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics.Metrics;
namespace MyWebApi.Controllers;
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
private readonly Counter<int> _requestCounter;
public WeatherForecastController(ILogger<WeatherForecastController> logger, IMeterFactory meterFactory)
{
_logger = logger;
var meter = meterFactory.Create("MyWebApi.Requests");
_requestCounter = meter.CreateCounter<int>("http.requests.count", "requests", "Counts incoming HTTP requests.");
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
_requestCounter.Add(1);
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
- We inject IMeterFactory into the controller's constructor.
- We create a Meter with a meaningful name ("MyWebApi.Requests").
- We create a Counter to track the request count.
- We increment the counter each time the endpoint is called.
- Remember to use descriptive names and units.
4. Visualizing Metrics in Azure Application Insights
After deploying your application to Azure, navigate to your Application Insights resource in the Azure portal.
- Metrics Explorer:
- Go to "Metrics" in the left-hand menu.
- In the "Metric Namespace" dropdown, you'll find your custom meter namespace ("MyWebApi.Requests" in our example).
- Select your counter ("http.requests.count").
- You can then visualize the request count over time.
*Logs (Analytics):
- Go to "Logs" in the left-hand menu.
- Use Kusto Query Language (KQL) to query your metrics data. For example:
customMetrics
| where customMetricName == "http.requests.count"
| summarize sum(valueCount) by bin(timestamp, 1m)
| render timechart
This query will display a time chart of the total request count aggregated by minute.
5. Adding Tags for Context
To add more context to your metrics, use tags:
_requestCounter.Add(1, new KeyValuePair<string, object>("http.method", "GET"));
Then, you can filter and aggregate metrics by these tags in Application Insights.
Best Practices
- Use meaningful meter and instrument names.
- Choose the appropriate instrument type (Counter, Gauge, Histogram).
- Leverage tags for filtering and aggregation.
- Use UCUM for units.
- Monitor Application Insights regularly.
By following these steps, you can effectively use IMeterFactory and Azure Application Insights to gain valuable insights into your .NET 8 ASP.NET Core application's performance. Happy monitoring!
Top comments (0)