backend/pkg/rpc/middle_ware.go

39 lines
1.4 KiB
Go
Raw Normal View History

2022-01-19 19:39:04 +08:00
package rpc
import (
"context"
"fmt"
"git.icechen.cn/monorepo/backend/pkg/env"
2022-01-23 14:48:44 +08:00
_ "git.icechen.cn/monorepo/backend/pkg/orm"
2022-01-19 19:39:04 +08:00
"github.com/gofiber/fiber/v2"
ctxLogger "github.com/luizsuper/ctxLoggers"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
"strings"
"time"
)
// Interceptor 将requestId 存入ctx记录出入参数记录时间
func Interceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler) (interface{}, error) {
serverName := env.Namespace + "-" + env.AppName + "-" + "service"
startTime := time.Now()
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
fmt.Printf("get metadata error")
}
if t, ok := md[strings.ToLower(fiber.HeaderXRequestID)]; ok {
ctx = context.WithValue(ctx, fiber.HeaderXRequestID, t[0])
}
ctxLogger.Debug(ctx, serverName, zap.String("gRPC method", fmt.Sprintf(" %s", info.FullMethod)), zap.Any("req", req))
resp, err := handler(ctx, req)
costSeconds := time.Since(startTime).Seconds()
if err != nil {
ctxLogger.Debug(ctx, serverName, zap.String("gRPC method", fmt.Sprintf(" %s", info.FullMethod)), zap.Float64("cost_time", costSeconds), zap.String("errorReason", err.Error()))
} else {
2022-01-23 14:48:44 +08:00
//ctxLogger.Debug(ctx, serverName, zap.String("gRPC method", fmt.Sprintf(" %s, %v", info.FullMethod, resp)), zap.Float64("cost_time", costSeconds), zap.Any("resp", resp))
2022-01-19 19:39:04 +08:00
}
return resp, err
}