你如何 read/log gRPC HTTP headers (不是自定义元数据)?

How do you read/log gRPC HTTP headers (not custom metadata)?

我正在使用 gRPC 和 Protobuf,使用 C++ 服务器和 C++ 客户端,以及 grpc-js 客户端。 有没有办法从 gRPC 的传输层读取所有 HTTP request/response headers? 我正在寻找那种典型的 client/server HTTP headers - 特别是,我想查看正在使用的协议版本(是否为 HTTP1.1/2)。我知道 gRPC 应该使用 HTTP2,但我试图在低级别确认它。

在典型的 gRPC 客户端实现中,您有这样的东西:

class PingPongClient {
 public:
  PingPongClient(std::shared_ptr<Channel> channel)
      : stub_(PingPong::NewStub(channel)) {}

  // Assembles the client's payload, sends it and presents the response back
  // from the server.
  PingPongReply PingPong(PingPongRequest request) {
    // Container for the data we expect from the server.
    PingPongReply reply;

    // Context for the client. It could be used to convey extra information to
    // the server and/or tweak certain RPC behaviors.
    ClientContext context;

    // The actual RPC.
    Status status = stub_->Ping(&context, request, &reply);

    // Act upon its status.
    if (status.ok()) {
        return reply;
    } else {
      auto errorMsg = status.error_code() + ": " + status.error_message();
      std::cout << errorMsg << std::endl;
      throw std::runtime_error(errorMsg);
    }
  }

 private:
  std::unique_ptr<PingPong::Stub> stub_;
};

在服务器端,类似于:

class PingPongServiceImpl final : public PingPong::Service {
  Status Ping(
    ServerContext* context,
    const PingPongRequest* request,
    PingPongReply* reply
  ) override {
    std::cout << "PingPong" << std::endl;
    printContextClientMetadata(context->client_metadata());

    if (request->input_msg() == "hello") {
      reply->set_output_msg("world");
    } else {
      reply->set_output_msg("I can't pong unless you ping me 'hello'!");
    }

    std::cout << "Replying with " << reply->output_msg() << std::endl;

    return Status::OK;
  }
};

我认为 ServerContext 或请求 object 可能可以访问此信息,但上下文似乎只提供一个到元数据的接口,这是自定义的。

grpc-io 论坛上 gRPC C++ examples give any indication that there is such an API, nor do any of the associated source/header files in the gRPC source code. I have exhausted my options here in terms of tutorials, blog posts, videos, and documentation - I asked a similar question

None,但无人问津。希望SO团队在这里有一些见解!

我还应该注意,我尝试将各种环境变量作为标志传递给 运行 进程,以查看是否可以获得有关 HTTP headers 的详细信息,但即使 [=15] =] 已启用(HTTP-related 个),我没有看到基本的 HTTP headers。

首先,gRPC 库绝对使用 HTTP/2。 The protocol is explicitly defined in terms of HTTP/2.

gRPC 库不会直接向应用程序公开原始 HTTP headers。但是,它们确实具有跟踪日志记录选项,可以记录各种用于调试目的的信息,包括 headers。可以通过设置环境变量 GRPC_TRACE 来启用跟踪器。还应设置环境变量 GRPC_VERBOSITY=DEBUG 以确保输出所有日志。可以在 this document describing how the library uses envinronment variables.

中找到更多信息

在 C++ 库中,http 跟踪器应记录原始 headers。 grpc-js 库具有不同的内部结构和不同的跟踪器定义,因此您应该为该库使用 call_stream 跟踪器。这些也会记录其他请求信息,但应该很容易找出 headers.