Change the span name to <method>_<request uri>

Use the same trace option for HTTPTransport
  fixes #15726
Signed-off-by: stonezdj <stonezdj@gmail.com>
This commit is contained in:
stonezdj 2021-10-13 17:25:17 +08:00
parent 4d89c845d0
commit 3b2ac06639
2 changed files with 22 additions and 10 deletions

View File

@ -16,6 +16,7 @@ package http
import (
"crypto/tls"
"github.com/goharbor/harbor/src/lib/trace"
"net"
"net/http"
"time"
@ -45,8 +46,8 @@ func init() {
}
func AddTracingWithGlobalTransport() {
insecureHTTPTransport = otelhttp.NewTransport(insecureHTTPTransport)
secureHTTPTransport = otelhttp.NewTransport(secureHTTPTransport)
insecureHTTPTransport = otelhttp.NewTransport(insecureHTTPTransport, trace.HarborHTTPTraceOptions...)
secureHTTPTransport = otelhttp.NewTransport(secureHTTPTransport, trace.HarborHTTPTraceOptions...)
}
// Use this instead of Default Transport in library because it sets ForceAttemptHTTP2 to true

View File

@ -34,7 +34,7 @@ func StartSpan(ctx context.Context, name string) (context.Context, oteltrace.Spa
return otel.Tracer("goharbor/harbor/src/lib/trace").Start(ctx, name)
}
// SpanFromContext returns the span from the context.
// SpanFromHTTPRequest returns the span from the context.
func SpanFromHTTPRequest(req *http.Request) oteltrace.Span {
ctx := req.Context()
return oteltrace.SpanFromContext(ctx)
@ -49,16 +49,27 @@ func RecordError(span oteltrace.Span, err error, description string) {
span.SetStatus(codes.Error, description)
}
// NewHandler returns a handler that wraps the given handler with tracing.
func NewHandler(h http.Handler, operation string) http.Handler {
httpOptions := []otelhttp.Option{
otelhttp.WithTracerProvider(otel.GetTracerProvider()),
otelhttp.WithPropagators(otel.GetTextMapPropagator()),
// HarborSpanNameFormatter common span name formatter in Harbor
func HarborSpanNameFormatter(operation string, r *http.Request) string {
if len(r.URL.Path) != 0 {
return r.Method + "_" + r.URL.Path
}
return otelhttp.NewHandler(h, operation, httpOptions...)
return operation
}
// StarTrace returns a new span with the given name.
// HarborHTTPTraceOptions common trace options
var HarborHTTPTraceOptions = []otelhttp.Option{
otelhttp.WithTracerProvider(otel.GetTracerProvider()),
otelhttp.WithPropagators(otel.GetTextMapPropagator()),
otelhttp.WithSpanNameFormatter(HarborSpanNameFormatter),
}
// NewHandler returns a handler that wraps the given handler with tracing.
func NewHandler(h http.Handler, operation string) http.Handler {
return otelhttp.NewHandler(h, operation, HarborHTTPTraceOptions...)
}
// StartTrace returns a new span with the given name.
func StartTrace(ctx context.Context, tracerName string, spanName string, opts ...oteltrace.SpanStartOption) (context.Context, oteltrace.Span) {
return otel.Tracer(tracerName).Start(ctx, spanName, opts...)
}