Search code examples
grpcgrpc-c++

How to get method name in gRPC C++ interceptor?


Documentation suggests that one of the most common applications of gRPC interceptors is logging. However, I cannot figure out how I can access the name of the method being called in grpcpp.

Is this a missing feature (grpc::experimental and all), or I am missing something?


GitHub issue #17520 seems to be addressing my point exactly, and it was closed with the following reply:

What you want can be achieved with the interception API.

Please refer https://github.com/grpc/grpc/blob/master/include/grpcpp/impl/codegen/interceptor.h for documentation

I couldn't find anything in <grpcpp/support/interceptor.h>, nor in the version of grpcpp/impl/codegen/interceptor.h at the time of maintainer's response.


Solution

  • You do need to use experimental features to get the RPC name inside an interceptor. Here is how I managed to print the method name when the RPC is called :

    #include <grpcpp/support/interceptor.h>
    #include <grpcpp/support/server_interceptor.h>
    
    #include <string>
    
    
    class LoggingInterceptor final : public grpc::experimental::Interceptor {
    public:
        explicit LoggingInterceptor(grpc::experimental::ServerRpcInfo *info) {
            const std::string method = info->method();
    
            if (method == "unknown") {
                std::cout << "Unimplemented Rpc called" << std::endl;
                return;
            }
    
            std::cout << "Rpc called : " << method << std::endl;
        }
    
        void Intercept(grpc::experimental::InterceptorBatchMethods *methods) override {
            methods->Proceed();
        }
    };
    
    class LoggingInterceptorFactory final : public grpc::experimental::ServerInterceptorFactoryInterface {
    public:
        grpc::experimental::Interceptor *CreateServerInterceptor(grpc::experimental::ServerRpcInfo *info) override {
            return new LoggingInterceptor(info);
        }
    };
    

    And when creating your ServerBuilder :

    std::vector<std::unique_ptr<grpc::experimental::ServerInterceptorFactoryInterface>> creators;
    creators.push_back(std::make_unique<LoggingInterceptorFactory>());
    builder.experimental().SetInterceptorCreators(std::move(creators));