backend/pkg/rpc/middle_ware.go
liuhaotian b3c49eaa34
All checks were successful
continuous-integration/drone/push Build is passing
feat : script service
2022-01-23 14:48:44 +08:00

39 lines
1.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package rpc
import (
"context"
"fmt"
"git.icechen.cn/monorepo/backend/pkg/env"
_ "git.icechen.cn/monorepo/backend/pkg/orm"
"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 {
//ctxLogger.Debug(ctx, serverName, zap.String("gRPC method", fmt.Sprintf(" %s, %v", info.FullMethod, resp)), zap.Float64("cost_time", costSeconds), zap.Any("resp", resp))
}
return resp, err
}