Created
September 16, 2018 06:45
-
-
Save amsokol/f41dc65c68eba00fcf66be616adb019e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
package middleware | |
import ( | |
"github.com/grpc-ecosystem/go-grpc-middleware" | |
"github.com/grpc-ecosystem/go-grpc-middleware/logging/zap" | |
"github.com/grpc-ecosystem/go-grpc-middleware/tags" | |
"go.uber.org/zap" | |
"go.uber.org/zap/zapcore" | |
"google.golang.org/grpc" | |
"google.golang.org/grpc/codes" | |
) | |
// codeToLevel redirects OK to DEBUG level logging instead of INFO | |
// This is example how you can log several gRPC code results | |
func codeToLevel(code codes.Code) zapcore.Level { | |
if code == codes.OK { | |
// It is DEBUG | |
return zap.DebugLevel | |
} | |
return grpc_zap.DefaultCodeToLevel(code) | |
} | |
// AddLogging returns grpc.Server config option that turn on logging. | |
func AddLogging(logger *zap.Logger, opts []grpc.ServerOption) []grpc.ServerOption { | |
// Shared options for the logger, with a custom gRPC code to log level function. | |
o := []grpc_zap.Option{ | |
grpc_zap.WithLevels(codeToLevel), | |
} | |
// Make sure that log statements internal to gRPC library are logged using the zapLogger as well. | |
grpc_zap.ReplaceGrpcLogger(logger) | |
// Add unary interceptor | |
opts = append(opts, grpc_middleware.WithUnaryServerChain( | |
grpc_ctxtags.UnaryServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)), | |
grpc_zap.UnaryServerInterceptor(logger, o...), | |
)) | |
// Add stream interceptor (added as an example here) | |
opts = append(opts, grpc_middleware.WithStreamServerChain( | |
grpc_ctxtags.StreamServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)), | |
grpc_zap.StreamServerInterceptor(logger, o...), | |
)) | |
return opts | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment