-
Notifications
You must be signed in to change notification settings - Fork 694
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
92 additions
and
62 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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)) | ||
} | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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"]) | ||
} |