Skip to content

Commit 20b4a64

Browse files
committed
fix zap logger example
1 parent bfde808 commit 20b4a64

File tree

4 files changed

+90
-70
lines changed

4 files changed

+90
-70
lines changed

interceptors/logging/examples/go.mod

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,27 +6,31 @@ require (
66
github.com/go-kit/log v0.2.1
77
github.com/go-logr/logr v1.2.4
88
github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.0.0
9-
github.com/phuslu/log v1.0.83
109
github.com/rs/zerolog v1.29.0
1110
github.com/sirupsen/logrus v1.9.0
11+
github.com/stretchr/testify v1.8.0
1212
go.uber.org/zap v1.24.0
1313
golang.org/x/exp v0.0.0-20230321023759-10a507213a29
1414
google.golang.org/grpc v1.53.0
1515
k8s.io/klog/v2 v2.90.1
1616
)
1717

1818
require (
19+
github.com/davecgh/go-spew v1.1.1 // indirect
1920
github.com/go-logfmt/logfmt v0.5.1 // indirect
2021
github.com/golang/protobuf v1.5.2 // indirect
2122
github.com/mattn/go-colorable v0.1.12 // indirect
2223
github.com/mattn/go-isatty v0.0.14 // indirect
24+
github.com/pkg/errors v0.9.1 // indirect
25+
github.com/pmezard/go-difflib v1.0.0 // indirect
2326
go.uber.org/atomic v1.7.0 // indirect
2427
go.uber.org/multierr v1.6.0 // indirect
2528
golang.org/x/net v0.8.0 // indirect
2629
golang.org/x/sys v0.6.0 // indirect
2730
golang.org/x/text v0.8.0 // indirect
2831
google.golang.org/genproto v0.0.0-20230110181048-76db0878b65f // indirect
2932
google.golang.org/protobuf v1.30.0 // indirect
33+
gopkg.in/yaml.v3 v3.0.1 // indirect
3034
)
3135

3236
replace github.com/grpc-ecosystem/go-grpc-middleware/v2 => ../../../

interceptors/logging/examples/go.sum

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,6 @@ github.com/mattn/go-colorable v0.1.12 h1:jF+Du6AlPIjs2BiUiQlKOX0rt3SujHxPnksPKZb
2020
github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
2121
github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y=
2222
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
23-
github.com/phuslu/log v1.0.83 h1:zfqz5tfFPLF8w0jEscpDxE2aFg1Y1kcbORDPliKdIbU=
24-
github.com/phuslu/log v1.0.83/go.mod h1:yAZh4pv6KxAsJDmJIcVSMxkMiUF7mJbpFN3vROkf0dc=
2523
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
2624
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
2725
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
3230
github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0=
3331
github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
3432
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
33+
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
3534
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
3635
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
36+
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
3737
github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk=
38+
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
3839
go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw=
3940
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
4041
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
6263
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
6364
google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng=
6465
google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
66+
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
6567
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
6668
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
6769
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
70+
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
6871
k8s.io/klog/v2 v2.90.1 h1:m4bYOKall2MmOiRaR1J+We67Do7vm9KiQVlT96lnHUw=
6972
k8s.io/klog/v2 v2.90.1/go.mod h1:y1WjHnz7Dj687irZUWR/WLkLc5N1YHtjLdmgWjndZn0=
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package examplezap
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging"
7+
"go.uber.org/zap"
8+
)
9+
10+
func InterceptorLogger(l *zap.Logger) logging.Logger {
11+
return logging.LoggerFunc(func(ctx context.Context, lvl logging.Level, msg string, fields ...any) {
12+
f := make([]zap.Field, 0, len(fields)/2)
13+
iter := logging.Fields(fields).Iterator()
14+
for iter.Next() {
15+
k, v := iter.At()
16+
f = append(f, zap.Any(k, v))
17+
}
18+
l = l.WithOptions(zap.AddCallerSkip(1)).With(f...)
19+
20+
switch lvl {
21+
case logging.LevelDebug:
22+
l.Debug(msg)
23+
case logging.LevelInfo:
24+
l.Info(msg)
25+
case logging.LevelWarn:
26+
l.Warn(msg)
27+
case logging.LevelError:
28+
l.Error(msg)
29+
default:
30+
panic(fmt.Sprintf("unknown level %v", lvl))
31+
}
32+
})
33+
}
Lines changed: 47 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -1,88 +1,68 @@
11
// Copyright (c) The go-grpc-middleware Authors.
22
// Licensed under the Apache License 2.0.
33

4-
package zap_test
4+
package examplezap_test
55

66
import (
77
"context"
8-
"fmt"
8+
examplezap "github.com/grpc-ecosystem/go-grpc-middleware/interceptors/logging/examples/zap"
9+
"runtime"
10+
"strings"
11+
"testing"
912

1013
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging"
14+
"github.com/grpc-ecosystem/go-grpc-middleware/v2/testing/testpb"
15+
"github.com/stretchr/testify/assert"
16+
"github.com/stretchr/testify/require"
17+
"github.com/stretchr/testify/suite"
1118
"go.uber.org/zap"
19+
"go.uber.org/zap/zaptest/observer"
1220
"google.golang.org/grpc"
1321
)
1422

15-
// InterceptorLogger adapts zap logger to interceptor logger.
16-
// This code is simple enough to be copied and not imported.
17-
func InterceptorLogger(l *zap.Logger) logging.Logger {
18-
return logging.LoggerFunc(func(ctx context.Context, lvl logging.Level, msg string, fields ...any) {
19-
f := make([]zap.Field, 0, len(fields)/2)
20-
21-
for i := 0; i < len(fields); i += 2 {
22-
key := fields[i]
23-
value := fields[i+1]
23+
type zapExampleTestSuite struct {
24+
*testpb.InterceptorTestSuite
25+
observedLogs *observer.ObservedLogs
26+
}
2427

25-
switch v := value.(type) {
26-
case string:
27-
f = append(f, zap.String(key.(string), v))
28-
case int:
29-
f = append(f, zap.Int(key.(string), v))
30-
case bool:
31-
f = append(f, zap.Bool(key.(string), v))
32-
default:
33-
f = append(f, zap.Any(key.(string), v))
34-
}
35-
}
28+
func TestSuite(t *testing.T) {
29+
if strings.HasPrefix(runtime.Version(), "go1.7") {
30+
t.Skipf("Skipping due to json.RawMessage incompatibility with go1.7")
31+
return
32+
}
33+
observedZapCore, observedLogs := observer.New(zap.DebugLevel)
34+
logger := examplezap.InterceptorLogger(zap.New(observedZapCore))
35+
s := &zapExampleTestSuite{
36+
InterceptorTestSuite: &testpb.InterceptorTestSuite{
37+
TestService: &testpb.TestPingService{},
38+
},
39+
observedLogs: observedLogs,
40+
}
3641

37-
logger := l.WithOptions(zap.AddCallerSkip(1)).With(f...)
42+
s.InterceptorTestSuite.ServerOpts = []grpc.ServerOption{
43+
grpc.StreamInterceptor(logging.StreamServerInterceptor(logger)),
44+
grpc.UnaryInterceptor(logging.UnaryServerInterceptor(logger)),
45+
}
3846

39-
switch lvl {
40-
case logging.LevelDebug:
41-
logger.Debug(msg)
42-
case logging.LevelInfo:
43-
logger.Info(msg)
44-
case logging.LevelWarn:
45-
logger.Warn(msg)
46-
case logging.LevelError:
47-
logger.Error(msg)
48-
default:
49-
panic(fmt.Sprintf("unknown level %v", lvl))
50-
}
51-
})
47+
suite.Run(t, s)
5248
}
5349

54-
func ExampleInterceptorLogger() {
55-
logger := zap.NewExample()
50+
func (s *zapExampleTestSuite) TestPing() {
51+
ctx := context.Background()
52+
_, err := s.Client.Ping(ctx, testpb.GoodPing)
53+
assert.NoError(s.T(), err, "there must be not be an on a successful call")
54+
require.Equal(s.T(), 2, s.observedLogs.Len())
55+
line := s.observedLogs.All()[0]
5656

57-
opts := []logging.Option{
58-
logging.WithLogOnEvents(logging.StartCall, logging.FinishCall),
59-
// Add any other option (check functions starting with logging.With).
60-
}
57+
contextMap := line.ContextMap()
58+
require.Equal(s.T(), zap.InfoLevel, line.Level)
59+
require.Equal(s.T(), "started call", line.Entry.Message)
6160

62-
// You can now create a server with logging instrumentation that e.g. logs when the unary or stream call is started or finished.
63-
_ = grpc.NewServer(
64-
grpc.ChainUnaryInterceptor(
65-
logging.UnaryServerInterceptor(InterceptorLogger(logger), opts...),
66-
// Add any other interceptor you want.
67-
),
68-
grpc.ChainStreamInterceptor(
69-
logging.StreamServerInterceptor(InterceptorLogger(logger), opts...),
70-
// Add any other interceptor you want.
71-
),
72-
)
73-
// ...user server.
61+
require.Equal(s.T(), "Ping", contextMap["grpc.method"])
62+
require.Equal(s.T(), "grpc", contextMap["protocol"])
63+
require.Equal(s.T(), "server", contextMap["grpc.component"])
7464

75-
// Similarly you can create client that will log for the unary and stream client started or finished calls.
76-
_, _ = grpc.Dial(
77-
"some-target",
78-
grpc.WithChainUnaryInterceptor(
79-
logging.UnaryClientInterceptor(InterceptorLogger(logger), opts...),
80-
// Add any other interceptor you want.
81-
),
82-
grpc.WithChainStreamInterceptor(
83-
logging.StreamClientInterceptor(InterceptorLogger(logger), opts...),
84-
// Add any other interceptor you want.
85-
),
86-
)
87-
// Output:
65+
require.Contains(s.T(), contextMap["peer.address"], "127.0.0.1")
66+
require.NotEmpty(s.T(), contextMap["grpc.start_time"])
67+
require.NotEmpty(s.T(), contextMap["grpc.time_ms"])
8868
}

0 commit comments

Comments
 (0)