我在 C# (NETCore) 中使用 gRPC。我想记录每个方法调用,并且我希望有某种方式一次拦截每个调用,而不是在每个服务方法上记录日志。怎么没找到,但是不存在一些拦截器的策略?
可以为客户端和服务器端定义自定义拦截器。在这两种情况下,您都需要创建一个继承自Interceptor类并覆盖要拦截的方法的新类。对于一个客户端拦截器是与整个客户端类连接的。在服务器端拦截器只为服务定义创建 - 这意味着如果你想拥有日志拦截器,你需要为每个服务定义指定它。此外,对于客户端,您可以使用带有 Func 的已有扩展方法作为参数,该方法可用于直接拦截场景(我不会向您展示它的代码,因为我现在无法访问它)。
下面是简单的拦截器:
public class GlobalServerLoggerInterceptor : Interceptor
{
private readonly ILogger logger;
public GlobalServerLoggerInterceptor(ILogger logger)
{
this.logger = logger;
}
public override async Task<TResponse> UnaryServerHandler<TRequest, TResponse>(TRequest request, ServerCallContext context, UnaryServerMethod<TRequest, TResponse> continuation)
{
logger.Debug($"{Environment.NewLine}GRPC Request{Environment.NewLine}Method: {context.Method}{Environment.NewLine}Data: {JsonConvert.SerializeObject(request, Formatting.Indented)}");
var response = await base.UnaryServerHandler(request, context, continuation);
logger.Debug($"{Environment.NewLine}GRPC Response{Environment.NewLine}Method: {context.Method}{Environment.NewLine}Data: {JsonConvert.SerializeObject(response, Formatting.Indented)}");
return response;
}
}
服务器端拦截器的初始化(伪代码):
var server = new Grpc.Core.Server
{
Services =
{
TestService.BindService(new TestImplementationService()).Intercept(IoC.Resolve<GlobalServerLoggerInterceptor>())
},
Ports = { new ServerPort("localhost", 1234, ServerCredentials.Insecure) }
};
在上面的例子中,你可能会注意到这样的语句:
.Intercept(IoC.Resolve<GlobalServerLoggerInterceptor>())
如果您的拦截器需要引用其他一些类,您需要在运行服务器之前初始化它们。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句