前提
了解一下asp.net core接入prometheus快速入门
https://blog.csdn.net/qq_36437991/article/details/139064138
新建.net 8空web项目
安装下面三个包
<PackageReference Include="OpenTelemetry.Exporter.Prometheus.AspNetCore" Version="1.8.0-rc.1" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.8.1" />
<PackageReference Include="System.Diagnostics.DiagnosticSource" Version="8.0.1" />
创建指标
HatCoMetrics.cs
using System.Diagnostics.Metrics;
namespace PrometheusStu03;
/// <summary>
/// 红帽子指标
/// </summary>
public class HatCoMetrics
{
private readonly Counter<int> _hatsSold;
public HatCoMetrics(IMeterFactory meterFactory)
{
//红帽子商店
var meter = meterFactory.Create("HatCo.Store");
//冲帽子商店销量
_hatsSold = meter.CreateCounter<int>("hatco.store.hats_sold",unit:"{hats}",description:"我们商店出售的帽子数量");
}
/// <summary>
/// 增加数量
/// </summary>
/// <param name="quantity"></param>
public void HatsSold(int quantity)
{
_hatsSold.Add(quantity);
}
}
指标收集
修改Program.cs
using OpenTelemetry.Metrics;
namespace PrometheusStu03;
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<HatCoMetrics>();
var app = builder.Build();
app.UseOpenTelemetryPrometheusScrapingEndpoint();
app.MapGet("/", (HatCoMetrics metrics) =>
{
//可以将销量存放到数据库中
metrics.HatsSold(1);
return "销售数量加1";
});
app.Run();
}
}
这样访问就能增加帽子的销量了
指标展示
修改Program.cs
using OpenTelemetry.Metrics;
namespace PrometheusStu03;
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<HatCoMetrics>();
builder.Services.AddOpenTelemetry()
.WithMetrics(builder2 =>
{
builder2.AddPrometheusExporter();
builder2.AddMeter("HatCo.Store");
});
var app = builder.Build();
app.UseOpenTelemetryPrometheusScrapingEndpoint();
app.MapGet("/", (HatCoMetrics metrics) =>
{
//可以将销量存放到数据库中
metrics.HatsSold(1);
return "销售数量加1";
});
app.Run();
}
}
展示内置指标
builder.Services.AddOpenTelemetry()
.WithMetrics(builder2 =>
{
builder2.AddPrometheusExporter();
builder2.AddMeter("Microsoft.AspNetCore.Hosting",
"Microsoft.AspNetCore.Server.Kestrel","HatCo.Store");
});
参考
创建指标
.net中的内置指标
asp.net core中的指标
.net中的常见指标
.net core指标收集