GRPC stdlib-only Logging Interceptor for Golang

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 standard library’s “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()

   h, err := handler(ctx, req)

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

   return h, err
}

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

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