using Grpc.Core.Interceptors; using Microsoft.Extensions.Logging; using System.Diagnostics; using FrontOffice.BFF.Application.Common.Interfaces; namespace FrontOffice.BFF.WebApi.Common.Behaviours; public class PerformanceBehaviour : Interceptor { private readonly Stopwatch _timer; private readonly ILogger _logger; private readonly ICurrentUserService _currentUserService; public PerformanceBehaviour(ILogger logger, ICurrentUserService currentUserService) { _timer = new Stopwatch(); _logger = logger; _currentUserService = currentUserService; } public override async Task UnaryServerHandler( TRequest request, ServerCallContext context, UnaryServerMethod continuation) { _timer.Start(); var response = await continuation(request, context); _timer.Stop(); var elapsedMilliseconds = _timer.ElapsedMilliseconds; if (elapsedMilliseconds > 500) { var requestName = typeof(TRequest).Name; var userId = _currentUserService.UserId; _logger.LogWarning("gRPC Long Running Request: {Name} ({ElapsedMilliseconds} milliseconds) {@UserId} {@Request}", requestName, elapsedMilliseconds, userId, request); } return response; } }