-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzap.go
48 lines (42 loc) · 1.21 KB
/
zap.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package main
import (
"context"
"github.com/grpc-ecosystem/go-grpc-middleware"
grpc_zap "github.com/grpc-ecosystem/go-grpc-middleware/logging/zap"
"github.com/grpc-ecosystem/go-grpc-middleware/tags"
pb "github.com/morix1500/sample-go-grpc-middleware/proto"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"google.golang.org/grpc"
"net"
"time"
)
type HelloService struct{}
func (h HelloService) Hello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloResponse, error) {
return &pb.HelloResponse{
Message: "Hello, " + in.Name,
}, nil
}
func main() {
opts := []grpc_zap.Option{
grpc_zap.WithDurationField(func(duration time.Duration) zapcore.Field {
return zap.Int64("grpc.time_ns", duration.Nanoseconds())
}),
}
zapLogger, _ := zap.NewProduction()
grpc_zap.ReplaceGrpcLogger(zapLogger)
s := grpc.NewServer(
grpc_middleware.WithUnaryServerChain(
grpc_ctxtags.UnaryServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),
grpc_zap.UnaryServerInterceptor(zapLogger, opts...),
),
)
pb.RegisterHelloServiceServer(s, HelloService{})
lis, err := net.Listen("tcp", ":5000")
if err != nil {
panic(err)
}
if err := s.Serve(lis); err != nil {
panic(err)
}
}