使用Docker、Prometheus和Grafana追踪Spotify指标

在WinampToSpotify项目中添加了.NET Aspire服务默认值和.NET Aspire AppHost后,添加了以下代码以在本地使用Docker Desktop运行Prometheus和Grafana。运行以下代码需要启动Docker Desktop。

// Prometheus容器,用于抓取应用指标
var prometheus = builder.AddContainer("prometheus", "prom/prometheus")
.WithBindMount("./prometheus/prometheus.yml", "/etc/prometheus/prometheus.yml")
.WithEndpoint(port: 9090, targetPort: 9090)
.WithArgs("--config.file=/etc/prometheus/prometheus.yml",
"--web.enable-otlp-receiver");
// 使用Prometheus作为数据源的Grafana容器
var grafana = builder.AddContainer("grafana", "grafana/grafana")
.WithVolume("grafana-storage", "/var/lib/grafana") // 持久化仪表板、用户、数据库
.WithVolume("grafana-provisioning", "/etc/grafana/provisioning", isReadOnly: true) // 可选:预配置YAML/JSON
.WithEndpoint(port: 3000, targetPort: 3000);

prometheus.yml是默认的Prometheus配置:

global:
  scrape_interval: 15s
  evaluation_interval: 15s
scrape_configs:
  - job_name: "otel-collector"
    static_configs:
      - targets: ["localhost:9090"]  # 如果使用Docker,请调整,例如 host.docker.internal:9464
    metrics_path: /metrics

创建了OpenTelemetryLib项目,并创建了一个ServiceCollection扩展方法来配置OTEL导出端点。安装了以下NuGet包:OpenTelemetry、OpenTelemetry.Exporter.Console、OpenTelemetry.Exporter.OpenTelemetryProtocol、OpenTelemetry.Exporter.Prometheus.HttpListener、OpenTelemetry.Instrumentation.Process。

var meterProviderBuilder = Sdk.CreateMeterProviderBuilder()
              .SetResourceBuilder(
                ResourceBuilder.CreateDefault().AddService("winamptospotifyweb", serviceVersion: "1.0.0"))
              .AddMeter(WinamptoSpotifyMetricsManager.MeterName)
              .AddOtlpExporter((options, metricReader) =>
              {
                  options.Protocol = OtlpExportProtocol.Grpc; // 4317作为gRPC端口。
                  options.ExportProcessorType = ExportProcessorType.Batch;
                  options.Endpoint = endpoint;
                  metricReader.PeriodicExportingMetricReaderOptions.ExportIntervalMilliseconds = 60000; // 1分钟
                  metricReader.PeriodicExportingMetricReaderOptions.ExportTimeoutMilliseconds = 30000; // 半分钟
              }) //Aspire Dashboard导出
              .AddOtlpExporter((exporterOptions, metricReaderOptions) =>
              {
                  exporterOptions.Endpoint = new Uri("http://localhost:9090/api/v1/otlp/v1/metrics");
                  exporterOptions.Protocol = OtlpExportProtocol.HttpProtobuf;
                  metricReaderOptions.PeriodicExportingMetricReaderOptions.ExportIntervalMilliseconds = 1000;
              }); //Prometheus导出

创建了Spotify指标类来注册Spotify服务相关的指标。开始跟踪每个文件夹添加的总曲目数。

public class SpotifyServiceMetrics : IWinampToSpotifyWebMetrics
{
    private readonly ISpotifyService _spotifyService;
    public SpotifyServiceMetrics(ISpotifyService spotifyService)
    {
        _spotifyService = spotifyService; 
    }
    public void RegisterMetrics(Meter meter)
    {
        var tracksAddedMetric = meter.CreateObservableGauge("winamptospotifyweb.spotifyservice.totaltracksadded", () => _spotifyService.GetPlaylistSummary().TotalTracksAdded,
        "unitless", "Number of tracks added");        
    }
}

WinamptoSpotifyMetricsManager类有助于注册指标,该类使用IMeterFactory进行注册。

public WinamptoSpotifyMetricsManager(IEnumerable<IWinampToSpotifyWebMetrics> metrics, IMeterFactory meterFactory)
{
    _metrics = metrics.ToImmutableList();
    _meter = meterFactory.Create(new MeterOptions(MeterName));
}

/// <summary>
///     注册WinampToSpotify实例中包含的所有自定义指标。
/// </summary>
public void Start()
{
    foreach (var metric in _metrics)
    {
        metric.RegisterMetrics(_meter);
    }
}

winamptospotifyweb.spotifyservice.totaltracksadded 指标已导出到 Aspire Dashboard、Prometheus 和 Grafana。

代码更改可以在 dotnet aspire added 和 opentelemetry and metrics added 提交中找到。
更多精彩内容 请关注我的个人公众号 公众号(办公AI智能小助手)或者 我的个人博客 https://blog.qife122.com/
对网络安全、黑客技术感兴趣的朋友可以关注我的安全公众号(网络安全技术点滴分享)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值