4

.NET 6: Enhance your gRPC client logs with a generic logging interceptor

 2 years ago
source link: https://anthonygiretti.com/2022/08/08/net-6-enhance-your-grpc-client-logs-with-a-generic-logging-interceptor/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

.NET 6: Enhance your gRPC client logs with a generic logging interceptor

2022-08-08 by anthonygiretti

Introduction

As you might suspect, logging what is happening in your application is good practice. In a gRPC client it is possible to automatically add logs to your application each time a gRPC endpoint is invoked without polluting your gRPC client. To do this, we will use a gRPC Interceptor to automatically log information on each call. As a reminder, Interceptors are a gRPC concept that allows apps to interact with incoming or outgoing gRPC calls. They offer a way to enrich the request processing pipeline.

Create an Interceptor to intercept calls client-side

To create a custom Interceptor, you will have to use the Interceptor class and inherit from it. To implement your logging, for each type of gRPC service, you will need to override a specific interception method, here they are:

  • AsyncClientStreamingCall for client streaming calls
  • AsyncDuplexStreamingCall for duplex (client and server) streaming calls
  • AsyncServerStreamingCall for server streaming calls
  • AsyncUnaryCall for unary calls

By adding logging (whatever you want), you can for example add logging execution date or the machine name that is performing the call, display request messages etc etc…

Configure the Interceptor

As you also know, magic does not exist. In this section I will show you how to attach your Interceptor to the gRPC client. First of all, what you need to know is that an Interceptor does not register in the .NET 6 dependency injection system, just like the ILogger interface passed to it. We will have to use the LoggerFactory factory to create the logger and inject it ourselves into the constructor of the Interceptor. Then we will attach everything to the gRPC typed client as follows:

Based on the logs you have added on your custom Interceptor, it should give something like this:

1-1024x96.png2-1024x83.png

Like this:

Loading...

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK