using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Azure.Functions.Worker; using Microsoft.Azure.Functions.Worker.Middleware; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using TEAMModelOS.SDK.DI; using static OpenXmlPowerTools.RevisionProcessor; using TEAMModelOS.SDK.Models; namespace TEAMModelOS { public class TimeMonitorMiddleware : IFunctionsWorkerMiddleware { private readonly AzureRedisFactory _azureRedis; public TimeMonitorMiddleware(AzureRedisFactory azureRedis) { _azureRedis = azureRedis; } public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next) { Stopwatch sw = new Stopwatch(); sw.Start(); await next(context); sw.Stop(); long st = sw.ElapsedMilliseconds; long costTime = st / 1000 ; string time = DateTimeOffset.Now.ToString("yyyyMMdd"); string name = context.FunctionDefinition.Name; string costkey = $"AzureFunction:Cost:{time}:{name}"; //超过1秒的 才记录执行时长 if (costTime > 1) { await _azureRedis.GetRedisClient(8).HashSetAsync(costkey, costTime, costTime); await _azureRedis.GetRedisClient(8).KeyExpireAsync(costkey, new TimeSpan(24, 0, 0)); } string countkey = $"AzureFunction:Count:{time}"; await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync(countkey, name, 1); await _azureRedis.GetRedisClient(8).KeyExpireAsync(countkey, new TimeSpan(24, 0, 0)); } } }