diff --git a/README.md b/README.md index 4be9cb5..b88db28 100644 --- a/README.md +++ b/README.md @@ -31,9 +31,16 @@ import ( ) func main() { + // With global Zerolog logger. grpc.NewServer( zerolog.UnaryInterceptor(), ) + + // With custom Zerolog instance. + log := zerolog.New(os.Stdout) + grpc.NewServer( + zerolog.UnaryInterceptorWithLogger(&log), + ) } ``` diff --git a/unary_interceptor.go b/unary_interceptor.go index 94f2721..ba5d76d 100644 --- a/unary_interceptor.go +++ b/unary_interceptor.go @@ -4,6 +4,8 @@ import ( "context" "time" + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" "google.golang.org/grpc" ) @@ -12,6 +14,10 @@ func UnaryInterceptor() grpc.ServerOption { return grpc.UnaryInterceptor(NewUnaryServerInterceptor()) } +func UnaryInterceptorWithLogger(log *zerolog.Logger) grpc.ServerOption { + return grpc.UnaryInterceptor(NewUnaryServerInterceptorWithLogger(log)) +} + // NewUnaryServerInterceptor that logs gRPC Requests using Zerolog. // { // ServiceField: "ExampleService", @@ -35,6 +41,10 @@ func UnaryInterceptor() grpc.ServerOption { // ZerologMessageField: "UnaryMessageDefault", // } func NewUnaryServerInterceptor() grpc.UnaryServerInterceptor { + return NewUnaryServerInterceptorWithLogger(&log.Logger) +} + +func NewUnaryServerInterceptorWithLogger(log *zerolog.Logger) grpc.UnaryServerInterceptor { return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { now := time.Now() resp, err := handler(ctx, req) diff --git a/unary_interceptor_test.go b/unary_interceptor_test.go index 428886c..15cea58 100644 --- a/unary_interceptor_test.go +++ b/unary_interceptor_test.go @@ -13,6 +13,7 @@ import ( type TestUnaryInterceptorSuite struct { suite.Suite out *bytes.Buffer + log zerolog.Logger client *test.TestClient } @@ -21,15 +22,17 @@ func TestUnaryServerInterceptor(t *testing.T) { } func (s *TestUnaryInterceptorSuite) SetupSuite() { + s.out = &bytes.Buffer{} + s.log = zerolog.New(s.out) go func() { - test.StartServer(NewUnaryServerInterceptor()) + test.StartServer(NewUnaryServerInterceptorWithLogger(&s.log)) }() s.client = test.GetClient() } func (s *TestUnaryInterceptorSuite) SetupTest() { s.out = &bytes.Buffer{} - log = zerolog.New(s.out) + s.log = zerolog.New(s.out) } func TestUnaryInterceptor(t *testing.T) { diff --git a/util.go b/util.go index 5d82559..4935c0e 100644 --- a/util.go +++ b/util.go @@ -62,7 +62,6 @@ var ( DetailsField = "details" // UnaryMessageDefault of logging messages from unary. UnaryMessageDefault = "unary" - log = zerolog.Logger{} ) // LogIncomingCall of gRPC method.