go-grpc-middleware icon indicating copy to clipboard operation
go-grpc-middleware copied to clipboard

grpc_ctxtags from metadata

Open graphaelli opened this issue 6 years ago • 1 comments

I'm trying to log some per-request metadata. The code below gets it done, producing:

grpc.code=OK grpc.method=Ping user=98765 peer.address=127.0.0.1:53878 span.kind=server system=grpc

I was wondering if there's a better way?

On the client side doing:


import "google.golang.org/grpc/metadata"

md := metadata.Pairs("user", "98765")
ctx := metadata.NewOutgoingContext(context.Background(), md)
client.Ping(ctx, &pb_testproto.PingRequest{})

And on the server, something like:

func UnaryServerMetdataTagInterceptor(fields ...string) grpc.UnaryServerInterceptor {
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
		if ctxMd, ok := metadata.FromIncomingContext(ctx); ok {
			for _, field := range fields {
				if values, present := ctxMd[field]; present {
					tags := grpc_ctxtags.Extract(ctx)
					tags = tags.Set(field, strings.Join(values, ","))
				}
			}
		}
		return handler(ctx, req)
	}
}

myServer := grpc.NewServer(
	grpc_middleware.WithUnaryServerChain(
		grpc_ctxtags.UnaryServerInterceptor(),
		UnaryServerMetdataTagInterceptor("user"),
		grpc_logrus.UnaryServerInterceptor(logrusEntry, logrusOpts...),
	),
	...
)

Related, is there a reason grpc_ctxtags. RequestFieldExtractorFunc doesn't get access to the per-request context? Would the addition of a MetadataExtractorFunc in grpc_ctxtags.options be welcomed?

graphaelli avatar Oct 20 '17 19:10 graphaelli

MetadataExtractorFunc sounds like a good extra options to the tags interceptors. Happy to review PRs! :)

mwitkow avatar Nov 04 '17 08:11 mwitkow

This is pretty old and we know have v2 code with different structure. Let us know if this is still important, we can reopen.

bwplotka avatar Mar 19 '23 01:03 bwplotka