feat: add tracing enrichment and prometheus exporter
This commit is contained in:
@@ -709,35 +709,37 @@ scrape_configs:
|
||||
- targets: ['node-exporter:9100']
|
||||
```
|
||||
|
||||
### 8.2 应用监控指标
|
||||
### 8.2 应用监控指标(OpenTelemetry + Prometheus Exporter)
|
||||
```csharp
|
||||
// Program.cs - 添加Prometheus监控
|
||||
builder.Services.AddPrometheusMetrics();
|
||||
// Program.cs - 指标与探针
|
||||
builder.Services.AddHealthChecks();
|
||||
builder.Services.AddOpenTelemetry()
|
||||
.WithMetrics(metrics =>
|
||||
{
|
||||
metrics
|
||||
.AddAspNetCoreInstrumentation()
|
||||
.AddHttpClientInstrumentation()
|
||||
.AddRuntimeInstrumentation()
|
||||
.AddPrometheusExporter(); // /metrics
|
||||
});
|
||||
|
||||
app.UseMetricServer(); // /metrics端点
|
||||
app.UseHttpMetrics(); // HTTP请求指标
|
||||
var app = builder.Build();
|
||||
app.MapHealthChecks("/healthz"); // 存活/就绪探针
|
||||
app.MapPrometheusScrapingEndpoint(); // 默认 /metrics
|
||||
```
|
||||
|
||||
// 自定义指标
|
||||
public class MetricsService
|
||||
自定义业务指标(使用 `System.Diagnostics.Metrics`,由 Prometheus Exporter 暴露):
|
||||
```csharp
|
||||
internal static class BusinessMetrics
|
||||
{
|
||||
private static readonly Counter OrderCreatedCounter = Metrics
|
||||
.CreateCounter("orders_created_total", "Total orders created");
|
||||
|
||||
private static readonly Histogram OrderProcessingDuration = Metrics
|
||||
.CreateHistogram("order_processing_duration_seconds", "Order processing duration");
|
||||
|
||||
public void RecordOrderCreated()
|
||||
{
|
||||
OrderCreatedCounter.Inc();
|
||||
}
|
||||
|
||||
public IDisposable MeasureOrderProcessing()
|
||||
{
|
||||
return OrderProcessingDuration.NewTimer();
|
||||
}
|
||||
private static readonly Meter Meter = new("TakeoutSaaS.App", "1.0.0");
|
||||
public static readonly Counter<long> OrdersCreated = Meter.CreateCounter<long>("orders_created_total", "个", "订单创建计数");
|
||||
public static readonly Histogram<double> OrderProcessingSeconds = Meter.CreateHistogram<double>("order_processing_duration_seconds", "s", "订单处理耗时");
|
||||
}
|
||||
```
|
||||
|
||||
Prometheus 抓取示例:见 `deploy/prometheus/prometheus.yml`,默认拉取 `/metrics`,告警规则见 `deploy/prometheus/alert.rules.yml`。
|
||||
|
||||
### 8.3 Grafana仪表板
|
||||
```json
|
||||
{
|
||||
@@ -1007,4 +1009,3 @@ docker-compose up -d --force-recreate --no-deps api
|
||||
docker pull takeout-saas-api:previous-version
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
|
||||
Reference in New Issue
Block a user