45 lines
1.7 KiB
C#
45 lines
1.7 KiB
C#
namespace MP.IOC.Services
|
|
{
|
|
|
|
public class MetricsFlushService : BackgroundService
|
|
{
|
|
private readonly RouteStatsManager _stats;
|
|
private readonly ILogger<MetricsFlushService> _logger;
|
|
private readonly IConfiguration _config;
|
|
|
|
public MetricsFlushService(RouteStatsManager stats, ILogger<MetricsFlushService> logger, IConfiguration config)
|
|
{
|
|
_stats = stats;
|
|
_logger = logger;
|
|
_config = config;
|
|
}
|
|
|
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
{
|
|
var interval = _config.GetValue<int>("RouteMan:FlushIntervalSeconds", 30);
|
|
while (!stoppingToken.IsCancellationRequested)
|
|
{
|
|
try
|
|
{
|
|
await Task.Delay(TimeSpan.FromSeconds(interval), stoppingToken);
|
|
var snapshot = _stats.Snapshot();
|
|
// Qui puoi serializzare e salvare su Redis/DB
|
|
// Esempio: loggare per ora
|
|
foreach (var kv in snapshot)
|
|
{
|
|
_logger.LogInformation("Method {method} Count {count} TotalDuration {duration} Destinations {dests}",
|
|
kv.Key, kv.Value.Count, kv.Value.TotalDuration, string.Join(",", kv.Value.Destinations.Select(x => $"{x.Key}:{x.Value}")));
|
|
}
|
|
// opzionale: _stats.Clear();
|
|
}
|
|
catch (TaskCanceledException) { }
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Error flushing metrics");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|