gRPC Interceptors: Logging, Auth and Metrics
On this page
What are gRPC interceptors?
Every handler needs the same things: verify the caller, log the call, record metrics, recover from panics. Copying that into each method is error-prone. An interceptor wraps every call, like HTTP middleware.
There are four kinds: unary and stream, each on the server and the client.
A server interceptor for auth and logging in Go
// authLog checks a bearer token and logs every unary call with its code and duration.
func authLog(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
start := time.Now()
var resp any
var err error
if strings.HasPrefix(info.FullMethod, "/grpc.health") || strings.HasPrefix(info.FullMethod, "/grpc.reflection") {
resp, err = handler(ctx, req) // public infrastructure endpoints
} else if md, _ := metadata.FromIncomingContext(ctx); len(md.Get("authorization")) == 0 ||
md.Get("authorization")[0] != "Bearer demo-token" {
err = status.Error(codes.Unauthenticated, "missing or invalid bearer token")
} else {
resp, err = handler(ctx, req)
}
log.Printf("unary %s code=%s took=%s", info.FullMethod, status.Code(err), time.Since(start).Round(time.Millisecond))
return resp, err
}
srv := grpc.NewServer(grpc.UnaryInterceptor(authLog))info.FullMethod(/shop.v1.OrderService/GetOrder) lets you apply rules per method.- Calling
handler(ctx, req)runs the next interceptor or the method; not calling it short-circuits the request. - Anything added to
ctx(the authenticated user, a request ID) is visible to the handler.
The log from the course's test run:
unary /shop.v1.OrderService/GetOrder code=OK took=0s
unary /shop.v1.OrderService/GetOrder code=NotFound took=0s
unary /shop.v1.OrderService/GetOrder code=InvalidArgument took=0s
unary /shop.v1.OrderService/GetOrder code=Canceled took=500ms
unary /shop.v1.OrderService/CreateOrder code=OK took=0sAnd a call without a token never reached the handler:
ERROR:
Code: Unauthenticated
Message: missing or invalid bearer token(A real service validates a JWT or uses mutual TLS identities, Day 17, rather than comparing a fixed string.)
Chaining interceptors and why order matters
Register several with grpc.ChainUnaryInterceptor(a, b, c); they run in that order on the way in and reverse order on the way out. Order matters:
- Recovery first (outermost), so a panic anywhere becomes an
INTERNALstatus instead of crashing the process. - Tracing and metrics next, so they measure everything, including rejected calls.
- Logging.
- Authentication and authorization, so unauthenticated calls are rejected before any business logic.
- Validation (for example with protovalidate rules declared in the
.proto).
The go-grpc-middleware project provides ready-made interceptors for logging, auth, recovery, rate limiting, retries and validation; OpenTelemetry provides tracing and metrics as a stats handler (Day 24).
Stream interceptors
Stream interceptors wrap the whole stream, not each message. To act per message (logging every Recv), wrap the ServerStream with your own type that overrides RecvMsg and SendMsg. Remember to register stream interceptors separately (grpc.StreamInterceptor or ChainStreamInterceptor): the lab's unary interceptor didn't check streaming calls, and grpcurl's WatchOrder call succeeded without a token. In production, auth must cover both.
Client interceptors
On the client side, interceptors add metadata (auth tokens, request IDs), set default deadlines (Day 15), record client-side latency, and implement custom retry logic.
Check yourself
It returns an error status, such as UNAUTHENTICATED, without calling the handler. The client receives that status and the handler never runs.
As the outermost wrapper, it catches panics from every later interceptor and the handler, turning them into an INTERNAL status.
Only a unary interceptor was registered. Streaming RPCs go through stream interceptors, so without one, streaming calls skipped authentication entirely.
Adding auth tokens and request ids to outgoing metadata, logging, recording metrics and applying retries on every call in one place. Application code then just calls methods without repeating that plumbing.