TimeMonitorMiddleware.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. using Microsoft.AspNetCore.Mvc.Filters;
  2. using Microsoft.Azure.Functions.Worker;
  3. using Microsoft.Azure.Functions.Worker.Middleware;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using TEAMModelOS.SDK.DI;
  11. using static OpenXmlPowerTools.RevisionProcessor;
  12. using TEAMModelOS.SDK.Models;
  13. namespace TEAMModelOS
  14. {
  15. public class TimeMonitorMiddleware : IFunctionsWorkerMiddleware
  16. {
  17. private readonly AzureRedisFactory _azureRedis;
  18. public TimeMonitorMiddleware(AzureRedisFactory azureRedis) {
  19. _azureRedis = azureRedis;
  20. }
  21. public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
  22. {
  23. Stopwatch sw = new Stopwatch();
  24. sw.Start();
  25. await next(context);
  26. sw.Stop();
  27. long st = sw.ElapsedMilliseconds;
  28. long costTime = st / 1000 ;
  29. string time = DateTimeOffset.Now.ToString("yyyyMMdd");
  30. string name = context.FunctionDefinition.Name;
  31. string costkey = $"AzureFunction:Cost:{time}:{name}";
  32. //超过1秒的 才记录执行时长
  33. if (costTime > 1) {
  34. await _azureRedis.GetRedisClient(8).HashSetAsync(costkey, costTime, costTime);
  35. await _azureRedis.GetRedisClient(8).KeyExpireAsync(costkey, new TimeSpan(24, 0, 0));
  36. }
  37. string countkey = $"AzureFunction:Count:{time}";
  38. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync(countkey, name, 1);
  39. await _azureRedis.GetRedisClient(8).KeyExpireAsync(countkey, new TimeSpan(24, 0, 0));
  40. }
  41. }
  42. }