[hw-7] add metrics, tracing

This commit is contained in:
Никита Шубин
2025-07-26 14:15:40 +00:00
parent 342bd3f726
commit 4396bebe80
38 changed files with 717 additions and 36 deletions

View File

@@ -0,0 +1,43 @@
package mw
import (
"context"
"strings"
"time"
"route256/loms/internal/infra/grpc/metrics"
"google.golang.org/grpc"
"google.golang.org/grpc/status"
)
const UNKNOWN = "unknown"
func WithMetrics(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) {
start := time.Now()
resp, err = handler(ctx, req)
// "/pkg.Service/Method"
service, method := parseFullMethod(info.FullMethod)
code := status.Code(err).String()
metrics.IncRequestHandlerCount(service, method, code)
metrics.StoreHandlerRequestDuration(service, method, code, time.Since(start))
return resp, err
}
func parseFullMethod(full string) (service, method string) {
if full == "" {
return UNKNOWN, UNKNOWN
}
full = strings.TrimPrefix(full, "/")
slash := strings.Index(full, "/")
if slash < 0 {
return full, UNKNOWN
}
return full[:slash], full[slash+1:]
}

View File

@@ -0,0 +1,38 @@
package mw
import (
"context"
"strings"
"go.opentelemetry.io/otel/codes"
"google.golang.org/grpc"
"google.golang.org/grpc/status"
"route256/loms/internal/infra/tracing"
)
func WithTracing(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
service, method := splitFullMethod(info.FullMethod)
ctx, span := tracing.Tracer().Start(ctx, service+"/"+method)
defer span.End()
resp, err := handler(ctx, req)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, status.Convert(err).Message())
} else {
span.SetStatus(codes.Ok, "OK")
}
return resp, err
}
func splitFullMethod(full string) (service, method string) {
full = strings.TrimPrefix(full, "/")
if i := strings.Index(full, "/"); i >= 0 {
return full[:i], full[i+1:]
}
return "unknown", full
}