2024-08-06 22:13:37 +07:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-08-15 09:36:06 +07:00
|
|
|
"errors"
|
2024-08-06 22:13:37 +07:00
|
|
|
"fmt"
|
|
|
|
"log/slog"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"connectrpc.com/connect"
|
|
|
|
"github.com/tigorlazuardi/bluemage/go/pkg/errs"
|
2024-08-12 20:20:12 +07:00
|
|
|
"github.com/tigorlazuardi/bluemage/go/pkg/telemetry"
|
|
|
|
"go.opentelemetry.io/otel/trace"
|
2024-08-06 22:13:37 +07:00
|
|
|
)
|
|
|
|
|
|
|
|
func LogInterceptor() connect.UnaryInterceptorFunc {
|
|
|
|
interceptor := func(next connect.UnaryFunc) connect.UnaryFunc {
|
2024-08-12 20:20:12 +07:00
|
|
|
return func(ctx context.Context, ar connect.AnyRequest) (resp connect.AnyResponse, err error) {
|
|
|
|
span := trace.SpanFromContext(ctx)
|
|
|
|
defer func() { telemetry.EndWithStatus(span, err) }()
|
|
|
|
|
2024-08-06 22:13:37 +07:00
|
|
|
start := time.Now()
|
2024-08-12 20:20:12 +07:00
|
|
|
resp, err = next(ctx, ar)
|
2024-08-06 22:13:37 +07:00
|
|
|
dur := time.Since(start)
|
|
|
|
if err != nil {
|
2024-08-08 13:41:18 +07:00
|
|
|
slog.ErrorContext(ctx, "RPC Error",
|
2024-08-06 22:13:37 +07:00
|
|
|
"procedure", ar.Spec().Procedure,
|
|
|
|
"method", ar.HTTPMethod(),
|
2024-08-12 22:00:21 +07:00
|
|
|
"duration", fmt.Sprintf("%.3fs", dur.Seconds()),
|
2024-08-06 22:13:37 +07:00
|
|
|
"error", errs.DrillToError(err),
|
2024-08-12 20:20:12 +07:00
|
|
|
"span.id", span.SpanContext().SpanID().String(),
|
|
|
|
"trace.id", span.SpanContext().TraceID().String(),
|
2024-08-06 22:13:37 +07:00
|
|
|
)
|
|
|
|
} else {
|
2024-08-08 13:41:18 +07:00
|
|
|
slog.InfoContext(ctx, "RPC Call",
|
2024-08-06 22:13:37 +07:00
|
|
|
"procedure", ar.Spec().Procedure,
|
|
|
|
"method", ar.HTTPMethod(),
|
2024-08-12 22:00:21 +07:00
|
|
|
"duration", fmt.Sprintf("%.3fs", dur.Seconds()),
|
2024-08-12 20:20:12 +07:00
|
|
|
"span.id", span.SpanContext().SpanID().String(),
|
|
|
|
"trace.id", span.SpanContext().TraceID().String(),
|
2024-08-06 22:13:37 +07:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
return resp, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return connect.UnaryInterceptorFunc(interceptor)
|
|
|
|
}
|
2024-08-15 09:36:06 +07:00
|
|
|
|
|
|
|
func ErrorMessageInterceptor() connect.UnaryInterceptorFunc {
|
|
|
|
return func(uf connect.UnaryFunc) connect.UnaryFunc {
|
|
|
|
return func(ctx context.Context, ar connect.AnyRequest) (connect.AnyResponse, error) {
|
|
|
|
resp, err := uf(ctx, ar)
|
|
|
|
if err == nil {
|
|
|
|
return resp, err
|
|
|
|
}
|
|
|
|
span := trace.SpanFromContext(ctx)
|
|
|
|
if !span.SpanContext().IsValid() {
|
|
|
|
return resp, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if cerr := new(connect.Error); errors.As(err, &cerr) {
|
|
|
|
if e := errs.FindError(cerr); e != nil {
|
|
|
|
msg := e.GetMessage()
|
|
|
|
e.Message("[%s] %s", span.SpanContext().SpanID().String(), msg)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return resp, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|