Initial version
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
namespace EonaCat.gRPC.Api.Middleware.Interceptors;
|
||||
|
||||
public class LoggerInterceptor : Interceptor
|
||||
{
|
||||
private readonly ILogger<LoggerInterceptor> _logger;
|
||||
|
||||
public LoggerInterceptor(ILogger<LoggerInterceptor> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
|
||||
public override async Task<TResponse> UnaryServerHandler<TRequest, TResponse>(
|
||||
TRequest request,
|
||||
ServerCallContext context,
|
||||
UnaryServerMethod<TRequest, TResponse> continuation)
|
||||
{
|
||||
LogCall(context);
|
||||
try
|
||||
{
|
||||
return await continuation(request, context);
|
||||
}
|
||||
catch (SqlException e)
|
||||
{
|
||||
_logger.LogError(e, $"An SQL error occurred when calling {context.Method}");
|
||||
Status status = e.Number == -2
|
||||
? new Status(StatusCode.DeadlineExceeded, $"SQL timeout: {e.Message}")
|
||||
: new Status(StatusCode.Internal, $"SQL error: {e.Message}");
|
||||
|
||||
throw new RpcException(status, e.Message);
|
||||
}
|
||||
catch (RpcException e)
|
||||
{
|
||||
_logger.LogError(e, $"gRPC error when calling {context.Method}: {e.Status.Detail}");
|
||||
throw;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.LogError(e, $"An error occurred when calling {context.Method}");
|
||||
throw new RpcException(Status.DefaultCancelled, e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private void LogCall(ServerCallContext context)
|
||||
{
|
||||
var httpContext = context.GetHttpContext();
|
||||
_logger.LogDebug($"Starting call. Request: {httpContext.Request.Path}");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user