Skip to content

Commit

Permalink
add zap and test
Browse files Browse the repository at this point in the history
  • Loading branch information
g4zhuj committed Apr 20, 2018
1 parent 239543c commit 370cd44
Show file tree
Hide file tree
Showing 7 changed files with 74 additions and 57 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
.vscode
examples/client/client
examples/server/server
72 changes: 29 additions & 43 deletions config/config.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
package config

import (
"sync/atomic"
"unsafe"

etcd "github.com/coreos/etcd/clientv3"
"github.com/g4zhuj/grpc-wrapper/plugins"
"github.com/g4zhuj/grpc-wrapper/server"
Expand Down Expand Up @@ -64,8 +61,8 @@ type LoggerConfig struct {
type OpenTracingConfig struct {
}

// 设置日志最低等级
func setLogConsole(levelStr string) (level zapcore.Level, err error) {
//
func convertLogLevel(levelStr string) (level zapcore.Level) {
switch levelStr {
case "debug":
level = zap.DebugLevel
Expand All @@ -79,19 +76,28 @@ func setLogConsole(levelStr string) (level zapcore.Level, err error) {
return
}

func (lconf *LoggerConfig) NewLogger() {
proConf := zapcore.EncoderConfig{
TimeKey: config.TimeKey,
LevelKey: config.LevelKey,
NameKey: "logger",
CallerKey: config.CallerKey,
MessageKey: config.MessageKey,
StacktraceKey: config.TraceKey,
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: zapcore.CapitalLevelEncoder,
EncodeTime: timeEncoder,
EncodeDuration: zapcore.SecondsDurationEncoder,
//NewDefaultLoggerConfig create a default config
func NewDefaultLoggerConfig() *LoggerConfig {
return &LoggerConfig{
Level: "debug",
Filename: "./logs",
MaxSize: 1,
MaxAge: 1,
MaxBackups: 10,
}
}

// 日志时间格式
// func timeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
// enc.AppendString(t.Format("2006-01-02 15:04:05"))
// }
//NewLogger create logger by config
func (lconf *LoggerConfig) NewLogger() *plugins.ZapLogger {
if lconf.Filename == "" {
logger, _ := zap.NewProduction(zap.AddCallerSkip(2))
return plugins.NewZapLogger(logger)
}

enCfg := zap.NewProductionEncoderConfig()
if lconf.CallFull {
enCfg.EncodeCaller = zapcore.FullCallerEncoder
Expand All @@ -101,40 +107,20 @@ func (lconf *LoggerConfig) NewLogger() {
zapcore.NewConsoleEncoder(enCfg)
}

if config.CallFull {
proConf.EncodeCaller = zapcore.FullCallerEncoder
} else {
proConf.EncodeCaller = zapcore.ShortCallerEncoder
}

//zapWriter := zapcore.
zapWriter := zapcore.AddSync(&lumberjack.Logger{
Filename: lconf.Filename,
MaxSize: lconf.MaxSize,
MaxAge: lconf.MaxAge,
MaxBackups: lconf.MaxBackups,
LocalTime: lconf.LocalTime,
})
// var writer zapcore.WriteSyncer
// writers := []zapcore.WriteSyncer{}
// writers = append(writers, zapWriter)
// output := zapcore.NewMultiWriteSyncer(writers...)

//设置日志等级
newCore := zapcore.NewCore(encoder, zapWriter, zap.NewAtomicLevelAt(lconf.Level))
opts := []zap.Option{zap.ErrorOutput(writer)}
opts = append(opts, zap.AddCaller(), zap.AddCallerSkip(1))
if config.TraceOpen {
opts = append(opts, zap.AddStacktrace(config.TraceLevel))
}
zaploger := zap.New(newCore, opts...)
if ZapLogger == nil {
ZapLogger = zaploger
} else {
oldLoger := ZapLogger
atomic.SwapPointer((*unsafe.Pointer)(unsafe.Pointer(&ZapLogger)), unsafe.Pointer(zaploger))
oldLoger.Sync()
}

newCore := zapcore.NewCore(encoder, zapWriter, zap.NewAtomicLevelAt(convertLogLevel(lconf.Level)))
opts := []zap.Option{zap.ErrorOutput(zapWriter)}
opts = append(opts, zap.AddCaller(), zap.AddCallerSkip(2))
logger := zap.New(newCore, opts...)
return plugins.NewZapLogger(logger)
}

//NewServer new server wrapper with config
Expand Down
26 changes: 19 additions & 7 deletions examples/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@ package main

import (
"context"
"fmt"
"log"
"os"
"time"

"github.com/g4zhuj/grpc-wrapper/config"
"google.golang.org/grpc"
"google.golang.org/grpc/grpclog"

"github.com/g4zhuj/grpc-wrapper/config"

pb "google.golang.org/grpc/examples/helloworld/helloworld"
)

Expand All @@ -20,15 +21,26 @@ func main() {

r, err := cfg.NewResolver()
if err != nil {
fmt.Printf("new registry err %v \n", err)
grpclog.Errorf("new registry err %v \n", err)
return
}

//set logger
logcfg := config.LoggerConfig{
Level: "debug",

// Filename: "./logs",
// MaxSize: 1,
// MaxAge: 1,
// MaxBackups: 10,
}
grpclog.SetLoggerV2(logcfg.NewLogger())

b := grpc.RoundRobin(r)
//time.Sleep(time.Second * 1)
conn, err := grpc.Dial("test", grpc.WithTimeout(time.Second*3), grpc.WithBalancer(b), grpc.WithInsecure(), grpc.WithBlock())
if err != nil {
fmt.Printf("Dial err %v\n", err)
grpclog.Errorf("Dial err %v\n", err)
return
}

Expand All @@ -43,9 +55,9 @@ func main() {
for i := 0; i < 20; i++ {
rsp, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name})
if err != nil {
log.Fatalf("could not greet: %v", err)
grpclog.Errorf("could not greet: %v", err)
}
log.Printf("Greeting: %s", rsp.Message)
grpclog.Infof("Greeting: %s", rsp.Message)
time.Sleep(time.Second * 5)
}
}
8 changes: 7 additions & 1 deletion examples/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"context"
"fmt"

"google.golang.org/grpc/grpclog"

"github.com/g4zhuj/grpc-wrapper/config"
pb "google.golang.org/grpc/examples/helloworld/helloworld"
)
Expand All @@ -12,7 +14,7 @@ type grpcserver struct{}

// SayHello implements helloworld.GreeterServer
func (s *grpcserver) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
fmt.Printf("receive ctx %v, req : %v \n", ctx, *in)
grpclog.Infof("receive req : %v \n", *in)
return &pb.HelloReply{Message: "Hello " + in.Name}, nil
}

Expand All @@ -21,6 +23,10 @@ func main() {
Endpoints: []string{"http://127.0.0.1:2379"},
}

//set zap logger
logcfg := config.LoggerConfig{}
grpclog.SetLoggerV2(logcfg.NewLogger())

reg, err := cfg.NewRegisty()
if err != nil {
fmt.Printf("new registry err %v \n", err)
Expand Down
8 changes: 6 additions & 2 deletions plugins/etcd.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"encoding/json"
"time"

"google.golang.org/grpc/grpclog"

"google.golang.org/grpc/codes"
"google.golang.org/grpc/naming"
"google.golang.org/grpc/status"
Expand Down Expand Up @@ -78,7 +80,8 @@ func (er *etcdRegistry) Register(ctx context.Context, target string, update nami
return err
}
etcdOpts := []etcd.OpOption{etcd.WithLease(lsRsp.ID)}
_, err = er.cli.KV.Put(ctx, target+"/"+update.Addr, string(upBytes), etcdOpts...)
key := target + "/" + update.Addr
_, err = er.cli.KV.Put(ctx, key, string(upBytes), etcdOpts...)
if err != nil {
return err
}
Expand All @@ -90,6 +93,7 @@ func (er *etcdRegistry) Register(ctx context.Context, target string, update nami
for {
_, ok := <-lsRspChan
if !ok {
grpclog.Fatalf("%v keepalive channel is closing", key)
break
}
}
Expand Down Expand Up @@ -123,7 +127,7 @@ func (ew *etcdWatcher) Next() ([]*naming.Update, error) {
updates = append(updates, &upt)
}
opts := []etcd.OpOption{etcd.WithRev(resp.Header.Revision + 1), etcd.WithPrefix(), etcd.WithPrevKV()}
ew.watchChan = ew.cli.Watch(ew.ctx, ew.target, opts...)
ew.watchChan = ew.cli.Watch(context.TODO(), ew.target, opts...)
return updates, nil
}

Expand Down
9 changes: 8 additions & 1 deletion plugins/zap.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ type ZapLogger struct {
logger *zap.Logger
}

func NewZapLogger(logger *zap.Logger) *ZapLogger {
return &ZapLogger{
logger: logger,
}
}

func (zl *ZapLogger) Info(args ...interface{}) {
zl.logger.Sugar().Info(args...)
}
Expand Down Expand Up @@ -57,6 +63,7 @@ func (zl *ZapLogger) Fatalf(format string, args ...interface{}) {
}

// V reports whether verbosity level l is at least the requested verbose level.
func (zl *ZapLogger) V(args ...interface{}) {
func (zl *ZapLogger) V(v int) bool {

return false
}
6 changes: 3 additions & 3 deletions server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ package server

import (
"context"
"fmt"
"net"

"google.golang.org/grpc/grpclog"

"google.golang.org/grpc"
"google.golang.org/grpc/naming"
"google.golang.org/grpc/reflection"
Expand Down Expand Up @@ -45,15 +46,14 @@ func (sw *ServerWrapper) Start() error {
return err
}
} else {
fmt.Println("registry is nil")
grpclog.Info("registry is nil")
}

// Register reflection service on gRPC server.
reflection.Register(sw.s)
if err := sw.s.Serve(lis); err != nil {
return err
}

return nil
}

Expand Down

0 comments on commit 370cd44

Please sign in to comment.