backend/pkg/rpc/middle_ware.go

38 lines
1.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package rpc
import (
"context"
"fmt"
"git.icechen.cn/monorepo/backend/pkg/env"
"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
}