enrich metrics snippet to project file

pull/30272/head
Rick Anderson 2023-09-07 12:46:33 -10:00
parent 62cf0d482d
commit f6164edac1
4 changed files with 46 additions and 29 deletions

View File

@ -97,35 +97,7 @@ ASP.NET Core has many built-in metrics. The `http.server.request.duration` metri
The `http.server.request.duration` metric supports tag enrichment using <xref:Microsoft.AspNetCore.Http.Features.IHttpMetricsTagsFeature>. Enrichment is when a library or app adds its own tags to a metric. This is useful if an app wants to add a custom categorization to dashboards or alerts built with metrics.
```cs
using Microsoft.AspNetCore.Http.Features;
var builder = WebApplication.CreateBuilder();
var app = builder.Build();
app.Use(async (context, next) =>
{
var tagsFeature = context.Features.Get<IHttpMetricsTagsFeature>();
if (tagsFeature != null)
{
var source = context.Request.Query["utm_medium"].ToString() switch
{
"" => "none",
"social" => "social",
"email" => "email",
"organic" => "organic",
_ => "other"
};
tagsFeature.Tags.Add(new KeyValuePair<string, object?>("mkt_medium", source));
}
await next.Invoke();
});
app.MapGet("/", () => "Hello World!");
app.Run();
```
:::code language="csharp" source="~/log-mon/metrics/metrics/samples/EnrichMetrics/Program.cs":::
The proceeding example:

View File

@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,27 @@
using Microsoft.AspNetCore.Http.Features;
var builder = WebApplication.CreateBuilder();
var app = builder.Build();
app.Use(async (context, next) =>
{
var tagsFeature = context.Features.Get<IHttpMetricsTagsFeature>();
if (tagsFeature != null)
{
var source = context.Request.Query["utm_medium"].ToString() switch
{
"" => "none",
"social" => "social",
"email" => "email",
"organic" => "organic",
_ => "other"
};
tagsFeature.Tags.Add(new KeyValuePair<string, object?>("mkt_medium", source));
}
await next.Invoke();
});
app.MapGet("/", () => "Hello World!");
app.Run();

View File

@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}