feat: replace App.Metrics with prometheus-net

This commit is contained in:
sam 2024-08-20 20:19:24 +02:00
parent df8af75dd4
commit be01fb1d53
8 changed files with 113 additions and 137 deletions

View file

@ -1,8 +1,9 @@
using App.Metrics;
using Catalogger.Backend.Bot.Commands;
using Catalogger.Backend.Database;
using Catalogger.Backend.Extensions;
using Catalogger.Backend.Services;
using Newtonsoft.Json.Serialization;
using Prometheus;
using Remora.Commands.Extensions;
using Remora.Discord.API.Abstractions.Gateway.Commands;
using Remora.Discord.Commands.Extensions;
@ -12,6 +13,7 @@ using Remora.Discord.Hosting.Extensions;
using Remora.Discord.Interactivity.Extensions;
using Remora.Discord.Pagination.Extensions;
using Serilog;
using Metrics = Prometheus.Metrics;
var builder = WebApplication.CreateBuilder(args);
var config = builder.AddConfiguration();
@ -50,10 +52,12 @@ builder.Host
.AddInteractionGroup<ChannelCommandsComponents>()
);
// Add metrics
// TODO: add actual reporter
var metricsBuilder = AppMetrics.CreateDefaultBuilder();
builder.Services.AddSingleton<IMetrics>(metricsBuilder.Build());
// Add metric server
// If metrics are disabled (Logging.EnableMetrics = false), also add a background service that updates
// metrics every minute, as some commands rely on them.
builder.Services.AddMetricServer(o => o.Port = (ushort)config.Logging.MetricsPort);
if (!config.Logging.EnableMetrics)
builder.Services.AddHostedService<BackgroundMetricsCollectionService>();
builder.Services
.AddDbContext<DatabaseContext>()
@ -68,6 +72,7 @@ await app.Initialize();
app.UseSerilogRequestLogging();
app.UseRouting();
app.UseHttpMetrics();
app.UseSwagger();
app.UseSwaggerUI();
app.UseCors();
@ -76,5 +81,9 @@ app.MapControllers();
app.Urls.Clear();
app.Urls.Add(config.Web.Address);
// Make sure metrics are updated whenever Prometheus scrapes them
Metrics.DefaultRegistry.AddBeforeCollectCallback(async ct =>
await app.Services.GetRequiredService<MetricsCollectionService>().CollectMetricsAsync(ct));
app.Run();
Log.CloseAndFlush();