This package supports the case where each request needs to be assigned its own unique request_id, allowing the request to be easily traced in logs as it goes from one service to another.
The Request-Id server interceptor will check for a Request-Id from incoming metadata, generating one if not present and inserting it into the context. Then it will also add it as a field to the context logger provided by the grpc_logrus package.
Request IDs are UUIDv4 values generated by Google's UUID package.
You can enable support for Request-Ids in your gRPC-Server by adding the interceptor to the middleware chain. However, the ordering is important. If you also use the grpc_logrus interceptor, the request-id middleware should be later in the middleware chain, but should also be before any other service middlewares to ensure it is present in the context to be included in those requests.
import (
...
...
"github.com/infobloxopen/atlas-app-toolkit/requestid"
)
func main() {
server := grpc.NewServer(
grpc.UnaryInterceptor(
grpc_middleware.ChainUnaryServer( // middleware chain
...
[grpc_logrus.UnaryServerInterceptor(logrus.NewEntry(logger)),]
requestid.UnaryServerInterceptor(), // Request-Id middleware
...
),
),
)
...
}
Once the middleware is included, the following function
rid, ok := requestid.FromContext(ctx)
can extract the request-id anywhere it is needed.
The ok
field returns whether the request id was actually found in the provided context.