Catalog My learning Blog
gRPC and Protobuf Tutorial: Fast Microservice APIs · Phase 3 · Lesson 16 · 3 min read

gRPC Interceptors: Logging, Auth and Metrics

On this page
  1. What are gRPC interceptors?
  2. A server interceptor for auth and logging in Go
  3. Chaining interceptors and why order matters
  4. Stream interceptors
  5. Client interceptors
  6. Check yourself

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

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:

Code
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=0s

And a call without a token never reached the handler:

YAML
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.)

Each call passes through a chain of interceptors before reaching the handler and back through them afterwards, so auth, logging, metrics and recovery apply to every method.
Each call passes through a chain of interceptors before reaching the handler and back through them afterwards, so auth, logging, metrics and recovery apply to every method.

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:

  1. Recovery first (outermost), so a panic anywhere becomes an INTERNAL status instead of crashing the process.
  2. Tracing and metrics next, so they measure everything, including rejected calls.
  3. Logging.
  4. Authentication and authorization, so unauthenticated calls are rejected before any business logic.
  5. 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.