/
Lexus_666
/
PIR_Lab_3
Обзор
Документация
Войти
/
Lexus_666
/
PIR_Lab_3
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
PIR_Lab_1/Middleware/StatisticsLoggingMiddleware.cs
83 строки
2 KB
MikhailPshenisnov
Добавлено внутреннее API
20 окт 2025, 04:49
20 окт 2025, 04:49
0815520
Код
Авторство
О чём код?
using PIR_Lab_1.Services; namespace PIR_Lab_1.Middleware; public class StatisticsLoggingMiddleware { private readonly RequestDelegate _next; private readonly IInternalApiClient _internalApiClient; private readonly ILogger<StatisticsLoggingMiddleware> _logger; private DateTime _lastStatisticsUpdate = DateTime.MinValue; private readonly TimeSpan _updateInterval = TimeSpan.FromMinutes(5); private readonly Lock _lock = new(); public StatisticsLoggingMiddleware( RequestDelegate next, IInternalApiClient internalApiClient, ILogger<StatisticsLoggingMiddleware> logger) { _next = next; _internalApiClient = internalApiClient; _logger = logger; } public async Task InvokeAsync(HttpContext context) { if (context.Request.Path.StartsWithSegments("/api/internal") || context.Request.Path.StartsWithSegments("/swagger")) { await _next(context); return; } await TryUpdateAndLogStatisticsAsync(); await _next(context); } private async Task TryUpdateAndLogStatisticsAsync() { var shouldUpdate = false; lock (_lock) { if (DateTime.UtcNow - _lastStatisticsUpdate >= _updateInterval) { shouldUpdate = true; _lastStatisticsUpdate = DateTime.UtcNow; } } if (shouldUpdate) { await UpdateAndLogStatisticsAsync(); } } private async Task UpdateAndLogStatisticsAsync() { try { _logger.LogDebug("Middleware is calling internal API for statistics..."); var statistics = await _internalApiClient.GetStatisticsFromInternalApiAsync(); if (statistics != null) { _logger.LogInformation( "Statistics: Completed {CompletedTasks}/{TotalTasks}. Last updated: {LastUpdated}", statistics.CompletedTasks, statistics.TotalTasks, statistics.LastUpdated.ToString("yyyy-MM-dd HH:mm:ss")); } else { _logger.LogWarning("Failed to get statistics from internal API"); } } catch (Exception ex) { _logger.LogError(ex, "Error in statistics logging middleware"); } } }