Minimal GRPC Logging Interceptor

It’s often the case where we need to write a small GRPC server whether be it a microservice or maybe a small weekend project.

Those type of projects we neither want to spend too much time on tooling and bootstrapping nor want the project to be filled with lots of dependencies.

Here is a small logging server interceptor for GRPC that only depends on the Golang standard library “log” package.

package main

import (
	"context"
	"google.golang.org/grpc"
	"time"
)

func LoggingInterceptor(
   ctx context.Context,
   req interface{},
   info *grpc.UnaryServerInfo,
   handler grpc.UnaryHandler) (interface{}, error) {
   start := time.Now()

   rsp, err := handler(ctx, req)

   log.Printf("grpc: method=%s\tduration=%s\terror=%v\treq=%v\trsp%v\n", info.FullMethod, time.Since(start), err, req, rsp)

   return rsp, err
}

You can use it when you are initialising the GRPC server like this.

grpcServer := grpc.NewServer(
	grpc.UnaryInterceptor(LoggingInterceptor,
)
comments powered by Disqus