From c53a4402fb2cfc65b167f82ff988171024d8e925 Mon Sep 17 00:00:00 2001 From: Bakhtiyor Ruziev Date: Mon, 8 May 2023 15:15:58 +0600 Subject: [PATCH] fix zap logger example --- interceptors/logging/examples/go.mod | 6 +- interceptors/logging/examples/go.sum | 7 +- interceptors/logging/examples/zap/example.go | 33 ++++++ .../logging/examples/zap/example_test.go | 108 ++++++++---------- 4 files changed, 92 insertions(+), 62 deletions(-) create mode 100644 interceptors/logging/examples/zap/example.go diff --git a/interceptors/logging/examples/go.mod b/interceptors/logging/examples/go.mod index 49d4a3e2c..0080ffc82 100644 --- a/interceptors/logging/examples/go.mod +++ b/interceptors/logging/examples/go.mod @@ -6,9 +6,9 @@ require ( github.com/go-kit/log v0.2.1 github.com/go-logr/logr v1.2.4 github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.0.0 - github.com/phuslu/log v1.0.83 github.com/rs/zerolog v1.29.0 github.com/sirupsen/logrus v1.9.0 + github.com/stretchr/testify v1.8.0 go.uber.org/zap v1.24.0 golang.org/x/exp v0.0.0-20230321023759-10a507213a29 google.golang.org/grpc v1.53.0 @@ -16,10 +16,13 @@ require ( ) require ( + github.com/davecgh/go-spew v1.1.1 // indirect github.com/go-logfmt/logfmt v0.5.1 // indirect github.com/golang/protobuf v1.5.2 // indirect github.com/mattn/go-colorable v0.1.12 // indirect github.com/mattn/go-isatty v0.0.14 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect go.uber.org/atomic v1.7.0 // indirect go.uber.org/multierr v1.6.0 // indirect golang.org/x/net v0.8.0 // indirect @@ -27,6 +30,7 @@ require ( golang.org/x/text v0.8.0 // indirect google.golang.org/genproto v0.0.0-20230110181048-76db0878b65f // indirect google.golang.org/protobuf v1.30.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect ) replace github.com/grpc-ecosystem/go-grpc-middleware/v2 => ../../../ diff --git a/interceptors/logging/examples/go.sum b/interceptors/logging/examples/go.sum index 04c905451..f4fe39e02 100644 --- a/interceptors/logging/examples/go.sum +++ b/interceptors/logging/examples/go.sum @@ -20,8 +20,6 @@ github.com/mattn/go-colorable v0.1.12 h1:jF+Du6AlPIjs2BiUiQlKOX0rt3SujHxPnksPKZb github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= -github.com/phuslu/log v1.0.83 h1:zfqz5tfFPLF8w0jEscpDxE2aFg1Y1kcbORDPliKdIbU= -github.com/phuslu/log v1.0.83/go.mod h1:yAZh4pv6KxAsJDmJIcVSMxkMiUF7mJbpFN3vROkf0dc= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= @@ -32,9 +30,12 @@ github.com/rs/zerolog v1.29.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6us github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0= github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/goleak v1.1.11 h1:wy28qYRKZgnJTxGxvye5/wgWr1EKjmUDGYox5mGlRlI= @@ -62,8 +63,10 @@ google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp0 google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng= google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= k8s.io/klog/v2 v2.90.1 h1:m4bYOKall2MmOiRaR1J+We67Do7vm9KiQVlT96lnHUw= k8s.io/klog/v2 v2.90.1/go.mod h1:y1WjHnz7Dj687irZUWR/WLkLc5N1YHtjLdmgWjndZn0= diff --git a/interceptors/logging/examples/zap/example.go b/interceptors/logging/examples/zap/example.go new file mode 100644 index 000000000..3ebf718c1 --- /dev/null +++ b/interceptors/logging/examples/zap/example.go @@ -0,0 +1,33 @@ +package examplezap + +import ( + "context" + "fmt" + "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging" + "go.uber.org/zap" +) + +func InterceptorLogger(l *zap.Logger) logging.Logger { + return logging.LoggerFunc(func(ctx context.Context, lvl logging.Level, msg string, fields ...any) { + f := make([]zap.Field, 0, len(fields)/2) + iter := logging.Fields(fields).Iterator() + for iter.Next() { + k, v := iter.At() + f = append(f, zap.Any(k, v)) + } + l = l.WithOptions(zap.AddCallerSkip(1)).With(f...) + + switch lvl { + case logging.LevelDebug: + l.Debug(msg) + case logging.LevelInfo: + l.Info(msg) + case logging.LevelWarn: + l.Warn(msg) + case logging.LevelError: + l.Error(msg) + default: + panic(fmt.Sprintf("unknown level %v", lvl)) + } + }) +} diff --git a/interceptors/logging/examples/zap/example_test.go b/interceptors/logging/examples/zap/example_test.go index 88a7b0d77..cde56c7ae 100644 --- a/interceptors/logging/examples/zap/example_test.go +++ b/interceptors/logging/examples/zap/example_test.go @@ -1,78 +1,68 @@ // Copyright (c) The go-grpc-middleware Authors. // Licensed under the Apache License 2.0. -package zap_test +package examplezap_test import ( "context" - "fmt" + examplezap "github.com/grpc-ecosystem/go-grpc-middleware/interceptors/logging/examples/zap" + "runtime" + "strings" + "testing" "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging" + "github.com/grpc-ecosystem/go-grpc-middleware/v2/testing/testpb" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/stretchr/testify/suite" "go.uber.org/zap" + "go.uber.org/zap/zaptest/observer" "google.golang.org/grpc" ) -// InterceptorLogger adapts zap logger to interceptor logger. -// This code is simple enough to be copied and not imported. -func InterceptorLogger(l *zap.Logger) logging.Logger { - return logging.LoggerFunc(func(ctx context.Context, lvl logging.Level, msg string, fields ...any) { - f := make([]zap.Field, 0, len(fields)/2) - for i := 0; i < len(fields); i += 2 { - i := logging.Fields(fields).Iterator() - if i.Next() { - k, v := i.At() - f = append(f, zap.Any(k, v)) - } - } - l = l.WithOptions(zap.AddCallerSkip(1)).With(f...) - - switch lvl { - case logging.LevelDebug: - l.Debug(msg) - case logging.LevelInfo: - l.Info(msg) - case logging.LevelWarn: - l.Warn(msg) - case logging.LevelError: - l.Error(msg) - default: - panic(fmt.Sprintf("unknown level %v", lvl)) - } - }) +type zapExampleTestSuite struct { + *testpb.InterceptorTestSuite + observedLogs *observer.ObservedLogs } -func ExampleInterceptorLogger() { - logger := zap.NewExample() +func TestSuite(t *testing.T) { + if strings.HasPrefix(runtime.Version(), "go1.7") { + t.Skipf("Skipping due to json.RawMessage incompatibility with go1.7") + return + } + observedZapCore, observedLogs := observer.New(zap.DebugLevel) + logger := examplezap.InterceptorLogger(zap.New(observedZapCore)) + s := &zapExampleTestSuite{ + InterceptorTestSuite: &testpb.InterceptorTestSuite{ + TestService: &testpb.TestPingService{}, + }, + observedLogs: observedLogs, + } - opts := []logging.Option{ - logging.WithLogOnEvents(logging.StartCall, logging.FinishCall), - // Add any other option (check functions starting with logging.With). + s.InterceptorTestSuite.ServerOpts = []grpc.ServerOption{ + grpc.StreamInterceptor(logging.StreamServerInterceptor(logger)), + grpc.UnaryInterceptor(logging.UnaryServerInterceptor(logger)), } - // You can now create a server with logging instrumentation that e.g. logs when the unary or stream call is started or finished. - _ = grpc.NewServer( - grpc.ChainUnaryInterceptor( - logging.UnaryServerInterceptor(InterceptorLogger(logger), opts...), - // Add any other interceptor you want. - ), - grpc.ChainStreamInterceptor( - logging.StreamServerInterceptor(InterceptorLogger(logger), opts...), - // Add any other interceptor you want. - ), - ) - // ...user server. + suite.Run(t, s) +} + +func (s *zapExampleTestSuite) TestPing() { + ctx := context.Background() + _, err := s.Client.Ping(ctx, testpb.GoodPing) + assert.NoError(s.T(), err, "there must be not be an on a successful call") + require.Equal(s.T(), 2, s.observedLogs.Len()) + line := s.observedLogs.All()[0] + + contextMap := line.ContextMap() + require.Equal(s.T(), zap.InfoLevel, line.Level) + require.Equal(s.T(), "started call", line.Entry.Message) + + require.Equal(s.T(), "Ping", contextMap["grpc.method"]) + require.Equal(s.T(), "grpc", contextMap["protocol"]) + require.Equal(s.T(), "server", contextMap["grpc.component"]) - // Similarly you can create client that will log for the unary and stream client started or finished calls. - _, _ = grpc.Dial( - "some-target", - grpc.WithChainUnaryInterceptor( - logging.UnaryClientInterceptor(InterceptorLogger(logger), opts...), - // Add any other interceptor you want. - ), - grpc.WithChainStreamInterceptor( - logging.StreamClientInterceptor(InterceptorLogger(logger), opts...), - // Add any other interceptor you want. - ), - ) - // Output: + require.Contains(s.T(), contextMap["peer.address"], "127.0.0.1") + require.NotEmpty(s.T(), contextMap["grpc.start_time"]) + require.NotEmpty(s.T(), contextMap["grpc.time_ms"]) }