- Option">
type Option - RequestFieldExtractorFunc">
type RequestFieldExtractorFunc - Tags">type Tags
grpc_ctxtags
将tag添加到ctx中,其他中间件可以用它添加关于请求的信息
Tags 描述了关于请求的相关信息,并且可以被其他中间件或处理程序设置和使用。标记用于记录和跟踪请求。标记在拦截处理程序堆栈中向上、和向下填充
对于一元方法和服务器流方法,传入’ WithFieldExtractor ‘选项。对于客户端流和双向流,您可以使用’ WithFieldExtractorForInitialReq ‘,它将从从客户端传递到服务器的第一个消息中提取标记。注意,不会为后续请求修改标记,所以这个选项只有在初始消息为流建立元数据时才有意义。
如果用户不使用初始化’ Tags ‘对象的拦截器,那么’ Extract(ctx) ‘之后的所有操作都将是无操作。这是为了确保代码在没有使用拦截器时不会恐慌。
e1:WithFieldExtractorForInitialReq
opts := []grpc_ctxtags.Option{
grpc_ctxtags.WithFieldExtractorForInitialReq(grpc_ctxtags.TagBasedRequestFieldExtractor("log_fields")),
}
_ = grpc.NewServer(
grpc.StreamInterceptor(grpc_ctxtags.StreamServerInterceptor(opts...)),
grpc.UnaryInterceptor(grpc_ctxtags.UnaryServerInterceptor(opts...)),
)
e2: WithFieldExtractor
opts := []grpc_ctxtags.Option{
grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.TagBasedRequestFieldExtractor("log_fields")),
}
_ = grpc.NewServer(
grpc.StreamInterceptor(grpc_ctxtags.StreamServerInterceptor(opts...)),
grpc.UnaryInterceptor(grpc_ctxtags.UnaryServerInterceptor(opts...)),
)
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
type RequestFieldExtractorFunc func(fullMethod string, req interface{}) map[string]interface{}
func TagBasedRequestFieldExtractor(tagName string) RequestFieldExtractorFunc
message Metadata {
repeated string tags = 1 [ (gogoproto.moretags) = "log_field:\"meta_tags\"" ];
}
- TagBasedRequestFieldExtractor是一个依赖Go结构标签从请求中导出日志字段的函数。这些通常来自协议插件,如Gogo protobuf
- tagName可以使用tagName变量进行配置。这里是“log_field”
type Tags
type Tags interface {
// Set sets the given key in the metadata tags.
Set(key string, value interface{}) Tags
// Has checks if the given key exists.
Has(key string) bool
// Values returns a map of key to values.
// Do not modify the underlying map, please use Set instead.
Values() map[string]interface{}
}