grpc_ctxtags 将tag添加到ctx中,其他中间件可以用它添加关于请求的信息

Tags 描述了关于请求的相关信息,并且可以被其他中间件或处理程序设置和使用。标记用于记录和跟踪请求。标记在拦截处理程序堆栈中向上、和向下填充

对于一元方法和服务器流方法,传入’ WithFieldExtractor ‘选项。对于客户端流和双向流,您可以使用’ WithFieldExtractorForInitialReq ‘,它将从从客户端传递到服务器的第一个消息中提取标记。注意,不会为后续请求修改标记,所以这个选项只有在初始消息为流建立元数据时才有意义。

如果用户不使用初始化’ Tags ‘对象的拦截器,那么’ Extract(ctx) ‘之后的所有操作都将是无操作。这是为了确保代码在没有使用拦截器时不会恐慌。

e1:WithFieldExtractorForInitialReq

  1. opts := []grpc_ctxtags.Option{
  2. grpc_ctxtags.WithFieldExtractorForInitialReq(grpc_ctxtags.TagBasedRequestFieldExtractor("log_fields")),
  3. }
  4. _ = grpc.NewServer(
  5. grpc.StreamInterceptor(grpc_ctxtags.StreamServerInterceptor(opts...)),
  6. grpc.UnaryInterceptor(grpc_ctxtags.UnaryServerInterceptor(opts...)),
  7. )

e2: WithFieldExtractor

  1. opts := []grpc_ctxtags.Option{
  2. grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.TagBasedRequestFieldExtractor("log_fields")),
  3. }
  4. _ = grpc.NewServer(
  5. grpc.StreamInterceptor(grpc_ctxtags.StreamServerInterceptor(opts...)),
  6. grpc.UnaryInterceptor(grpc_ctxtags.UnaryServerInterceptor(opts...)),
  7. )

func CodeGenRequestFieldExtractor(fullMethod string, req interface{}) map[string]interface{}

  • CodeGenRequestFieldExtractor是一个函数,它依赖于从请求中导出日志字段的代码生成函数
  • 这些通常来自协议插件,该插件基于自定义字段选项生成额外的信息。


func SetInContext(ctx context.Context, tags Tags) context.Context
func StreamServerInterceptor(opts …Option) grpc.StreamServerInterceptor
func UnaryServerInterceptor(opts …Option) grpc.UnaryServerInterceptor


type Option

func WithFieldExtractor(f RequestFieldExtractorFunc) Option

  • WithFieldExtractor定制了从protobuf消息中提取日志字段的函数,仅用于一元方法和服务器流方法

func WithFieldExtractorForInitialReq(f RequestFieldExtractorFunc) Option

  • WithFieldExtractorForInitialReq定制了从protobuf消息中提取日志字段的函数,用于所有的一元方法和流方法。对于客户端流和双向流,标记将从客户端第一个消息中提取


type RequestFieldExtractorFunc

RequestFieldExtractorFunc是一个用户提供的函数,它从gRPC请求中提取字段信息。它在到达单一请求或服务器流请求时从标记中间件调用。键和值将被添加到请求的上下文标记中。如果没有字段,则应该返回nil

  1. type RequestFieldExtractorFunc func(fullMethod string, req interface{}) map[string]interface{}

func TagBasedRequestFieldExtractor(tagName string) RequestFieldExtractorFunc

  1. message Metadata {
  2. repeated string tags = 1 [ (gogoproto.moretags) = "log_field:\"meta_tags\"" ];
  3. }
  • TagBasedRequestFieldExtractor是一个依赖Go结构标签从请求中导出日志字段的函数。这些通常来自协议插件,如Gogo protobuf
  • tagName可以使用tagName变量进行配置。这里是“log_field”

type Tags

  1. type Tags interface {
  2. // Set sets the given key in the metadata tags.
  3. Set(key string, value interface{}) Tags
  4. // Has checks if the given key exists.
  5. Has(key string) bool
  6. // Values returns a map of key to values.
  7. // Do not modify the underlying map, please use Set instead.
  8. Values() map[string]interface{}
  9. }

func Extract(ctx context.Context) Tags

  • Extracts返回上下文中已存在的Tags对象。如果在标记拦截器中没有设置上下文,则返回一个no-op的标记存储,它不会在上下文中传播。