Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

extract logging middleware #9

Merged
merged 12 commits into from
May 17, 2024
Prev Previous commit
Next Next commit
resolve service name from grpc method
  • Loading branch information
gimmyxd committed May 2, 2024
commit 3ee9ada14abdea6c1b1cee4513c2b315101244e4
24 changes: 22 additions & 2 deletions grpcutil/middlewares/tracing/tracing_middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@ package tracing

import (
"context"
"strings"
"time"

"github.com/aserto-dev/aserto-grpc/grpcutil"
"github.com/aserto-dev/header"
grpcmiddleware "github.com/grpc-ecosystem/go-grpc-middleware"
"github.com/rs/zerolog"
"golang.org/x/text/cases"
"golang.org/x/text/language"
"google.golang.org/grpc"
)

Expand All @@ -24,8 +27,25 @@ func (h tracingHook) Run(e *zerolog.Event, level zerolog.Level, msg string) {

serviceMethod, ok := grpc.Method(ctx)
if ok {
service := strings.SplitN(serviceMethod, "/", 2)[1]
serviceArr := strings.Split(service, ".")[1:4]
var serviceArrCap []string
for _, s := range serviceArr {
serviceArrCap = append(serviceArrCap, cases.Title(language.English, cases.Compact).String(s))
}
var serviceBuilder strings.Builder
for _, s := range serviceArrCap {
serviceBuilder.WriteString(s)
}
service = serviceBuilder.String()
if len(service) > 0 {
e.Str("service", service)
}

e.Str("method", serviceMethod)

}

}

func NewTracingMiddleware(logger *zerolog.Logger) *TracingMiddleware {
Expand All @@ -38,10 +58,10 @@ var _ grpcutil.Middleware = &TracingMiddleware{}

func (m *TracingMiddleware) Unary() grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
logger := m.logger.Hook(tracingHook{}).With().Interface("req", req).Ctx(ctx).Logger()
logger := m.logger.Hook(tracingHook{}).With().Interface("request", req).Ctx(ctx).Logger()
loggerCtx := logger.WithContext(ctx)

logger.Trace().Interface("request", req).Msg("grpc call start")
logger.Trace().Msg("grpc call start")

start := time.Now()
result, err := handler(loggerCtx, req)
Expand Down
Loading