traefik/pkg/middlewares/tracing/forwarder.go

60 lines
1.5 KiB
Go
Raw Normal View History

2018-01-10 16:48:04 +00:00
package tracing
import (
2018-11-14 09:18:03 +00:00
"context"
2018-01-10 16:48:04 +00:00
"net/http"
"github.com/opentracing/opentracing-go/ext"
"github.com/traefik/traefik/v2/pkg/log"
"github.com/traefik/traefik/v2/pkg/middlewares"
"github.com/traefik/traefik/v2/pkg/tracing"
2018-11-14 09:18:03 +00:00
)
const (
forwarderTypeName = "TracingForwarder"
2018-01-10 16:48:04 +00:00
)
type forwarderMiddleware struct {
2018-11-14 09:18:03 +00:00
router string
service string
next http.Handler
2018-01-10 16:48:04 +00:00
}
2018-11-14 09:18:03 +00:00
// NewForwarder creates a new forwarder middleware that traces the outgoing request.
func NewForwarder(ctx context.Context, router, service string, next http.Handler) http.Handler {
2019-09-13 17:28:04 +00:00
log.FromContext(middlewares.GetLoggerCtx(ctx, "tracing", forwarderTypeName)).
2018-11-14 09:18:03 +00:00
Debugf("Added outgoing tracing middleware %s", service)
2018-01-10 16:48:04 +00:00
return &forwarderMiddleware{
2018-11-14 09:18:03 +00:00
router: router,
service: service,
next: next,
2018-01-10 16:48:04 +00:00
}
}
2018-11-14 09:18:03 +00:00
func (f *forwarderMiddleware) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
tr, err := tracing.FromContext(req.Context())
if err != nil {
f.next.ServeHTTP(rw, req)
return
}
2018-01-10 16:48:04 +00:00
2018-11-14 09:18:03 +00:00
opParts := []string{f.service, f.router}
span, req, finish := tr.StartSpanf(req, ext.SpanKindRPCClientEnum, "forward", opParts, "/")
defer finish()
2018-01-10 16:48:04 +00:00
2022-02-10 15:00:09 +00:00
span.SetTag("traefik.service.name", f.service)
span.SetTag("traefik.router.name", f.router)
2018-11-14 09:18:03 +00:00
ext.HTTPMethod.Set(span, req.Method)
ext.HTTPUrl.Set(span, req.URL.String())
span.SetTag("http.host", req.Host)
2018-01-10 16:48:04 +00:00
2018-11-14 09:18:03 +00:00
tracing.InjectRequestHeaders(req)
2018-01-10 16:48:04 +00:00
2018-11-14 09:18:03 +00:00
recorder := newStatusCodeRecoder(rw, 200)
2018-11-14 09:18:03 +00:00
f.next.ServeHTTP(recorder, req)
2018-11-14 09:18:03 +00:00
tracing.LogResponseCode(span, recorder.Status())
}