Bluemage/go/server/interceptor.go

40 lines
973 B
Go
Raw Normal View History

package server
import (
"context"
"fmt"
"log/slog"
"time"
"connectrpc.com/connect"
"github.com/tigorlazuardi/bluemage/go/pkg/errs"
)
func LogInterceptor() connect.UnaryInterceptorFunc {
interceptor := func(next connect.UnaryFunc) connect.UnaryFunc {
return func(ctx context.Context, ar connect.AnyRequest) (connect.AnyResponse, error) {
start := time.Now()
resp, err := next(ctx, ar)
dur := time.Since(start)
millisecondsFloat := float64(dur) / float64(time.Millisecond)
if err != nil {
slog.Error("RPC Error",
"procedure", ar.Spec().Procedure,
"method", ar.HTTPMethod(),
"duration", fmt.Sprintf("%.3fs", millisecondsFloat),
"error", errs.DrillToError(err),
)
} else {
slog.Info("RPC Call",
"procedure", ar.Spec().Procedure,
"method", ar.HTTPMethod(),
"duration", fmt.Sprintf("%.3fs", millisecondsFloat),
)
}
return resp, err
}
}
return connect.UnaryInterceptorFunc(interceptor)
}