Documentation
¶
Overview ¶
Package otelhttp provides an http.Handler and functions that are intended to be used to add tracing by wrapping existing handlers.
Index ¶
- Constants
- func ContextWithClientLabeler(parent context.Context, l *Labeler) context.Context
- func ContextWithLabeler(parent context.Context, l *Labeler) context.Context
- func ContextWithStartTime(parent context.Context, start time.Time) context.Context
- func NewHandler(handler http.Handler, operation string, opts ...Option) http.Handler
- func NewMiddleware(operation string, opts ...Option) func(http.Handler) http.Handler
- func StartTimeFromContext(ctx context.Context) time.Time
- type Event
- type Filter
- type Labeler
- type Option
- func WithClientTrace(f func(context.Context) *httptrace.ClientTrace) Option
- func WithFilter(f Filter) Option
- func WithMessageEvents(events ...Event) Option
- func WithMeterProvider(provider metric.MeterProvider) Option
- func WithMetricAttributesFn(metricAttributesFn func(r *http.Request) []attribute.KeyValue) Optiondeprecated
- func WithPropagators(ps propagation.TextMapPropagator) Option
- func WithPublicEndpointFn(fn func(*http.Request) bool) Option
- func WithServerName(server string) Option
- func WithSpanNameFormatter(f func(operation string, r *http.Request) string) Option
- func WithSpanOptions(opts ...trace.SpanStartOption) Option
- func WithTracerProvider(provider trace.TracerProvider) Option
- type Transport
Examples ¶
Constants ¶
const ( // ReadBytesKey is the attribute key for the number of bytes returned by an // individual read from an HTTP request body. // // Deprecated: there is no direct semantic-convention replacement. ReadBytesKey = attribute.Key("http.read_bytes") // ReadErrorKey is the attribute key for the string form of a non-EOF error // returned while reading an HTTP request body. // // Deprecated: there is no direct semantic-convention replacement. ReadErrorKey = attribute.Key("http.read_error") // WroteBytesKey is the attribute key for the number of bytes returned by an // individual write to an HTTP response body. // // Deprecated: there is no direct semantic-convention replacement. WroteBytesKey = attribute.Key("http.wrote_bytes") // WriteErrorKey is the attribute key for the string form of a non-EOF error // returned while writing an HTTP response body. // // Deprecated: there is no direct semantic-convention replacement. WriteErrorKey = attribute.Key("http.write_error") )
Legacy HTTP attribute keys retained for compatibility.
const ScopeName = "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
ScopeName is the instrumentation scope name.
const Version = "0.72.0"
Version is the current release version of the otelhttp instrumentation.
Variables ¶
This section is empty.
Functions ¶
func ContextWithClientLabeler ¶ added in v0.72.0
ContextWithClientLabeler returns a new context with the provided Labeler instance for use with client-side HTTP instrumentation (otelhttp.Transport). Attributes added to this labeler will be attached to client-side metrics.
func ContextWithLabeler ¶ added in v0.53.0
ContextWithLabeler returns a new context with the provided Labeler instance. Attributes added to the specified labeler will be injected into metrics emitted by the instrumentation. Only one labeller can be injected into the context. Injecting it multiple times will override the previous calls.
func ContextWithStartTime ¶ added in v0.57.0
ContextWithStartTime returns a new context with the provided start time. The start time will be used for metrics and traces emitted by the instrumentation. Only one labeller can be injected into the context. Injecting it multiple times will override the previous calls.
func NewHandler ¶
NewHandler wraps the passed handler in a span named after the operation and enriches it with metrics.
Example ¶
package main
import (
"context"
"fmt"
"io"
"log"
"net/http"
"strings"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
)
func main() {
/* curl -v -d "a painting" http://localhost:7777/hello/bob/ross
...
* upload completely sent off: 10 out of 10 bytes
< HTTP/1.1 200 OK
< Traceparent: 00-76ae040ee5753f38edf1c2bd9bd128bd-dd394138cfd7a3dc-01
< Date: Fri, 04 Oct 2019 02:33:08 GMT
< Content-Length: 45
< Content-Type: text/plain; charset=utf-8
<
Hello, bob/ross!
You sent me this:
a painting
*/
figureOutName := func(ctx context.Context, s string) (string, error) {
pp := strings.SplitN(s, "/", 2)
var err error
switch pp[1] {
case "":
err = fmt.Errorf("expected /hello/:name in %q", s)
default:
trace.SpanFromContext(ctx).SetAttributes(attribute.String("name", pp[1]))
}
return pp[1], err
}
var mux http.ServeMux
mux.Handle(
"/hello/", http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
labeler, _ := otelhttp.LabelerFromContext(ctx)
var name string
// Wrap another function in its own span
if err := func(ctx context.Context) error {
ctx, span := trace.SpanFromContext(ctx).TracerProvider().Tracer("exampleTracer").Start(ctx, "figureOutName")
defer span.End()
var err error
name, err = figureOutName(ctx, r.URL.Path[1:])
return err
}(ctx); err != nil {
log.Println("error figuring out name: ", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
labeler.Add(attribute.Bool("error", true))
return
}
d, err := io.ReadAll(r.Body)
if err != nil {
log.Println("error reading body: ", err)
w.WriteHeader(http.StatusBadRequest)
labeler.Add(attribute.Bool("error", true))
return
}
n, err := io.WriteString(w, "Hello, "+name+"!\nYou sent me this:\n"+string(d))
if err != nil {
log.Printf("error writing reply after %d bytes: %s", n, err)
labeler.Add(attribute.Bool("error", true))
}
},
),
)
if err := http.ListenAndServe(
":7777",
otelhttp.NewHandler(
&mux, "server",
otelhttp.WithMessageEvents(otelhttp.ReadEvents, otelhttp.WriteEvents),
),
); err != nil {
log.Fatal(err)
}
}
Output:
func NewMiddleware ¶ added in v0.43.0
NewMiddleware returns a tracing and metrics instrumentation middleware. The handler returned by the middleware wraps a handler in a span named after the operation and enriches it with metrics.
func StartTimeFromContext ¶ added in v0.57.0
StartTimeFromContext retrieves a time.Time from the provided context if one is available. If no start time was found in the provided context, a new, zero start time is returned and the second return value is false.
Types ¶
type Event ¶ added in v0.64.0
type Event int
Event represents message event types for WithMessageEvents.
const ( ReadEvents Event WriteEvents )
Different types of events that can be recorded, see WithMessageEvents.
type Filter ¶
Filter is a predicate used to determine whether a given http.request should be traced. A Filter must return true if the request should be traced.
type Labeler ¶
type Labeler struct {
// contains filtered or unexported fields
}
Labeler is used to allow instrumented HTTP handlers to add custom attributes to the metrics recorded by the net/http instrumentation.
func ClientLabelerFromContext ¶ added in v0.72.0
ClientLabelerFromContext retrieves a Labeler instance from the provided context for use with client-side HTTP instrumentation. If no Labeler was found, a new, empty Labeler is returned and the second return value is false.
func LabelerFromContext ¶
LabelerFromContext retrieves a Labeler instance from the provided context if one is available. If no Labeler was found in the provided context a new, empty Labeler is returned and the second return value is false. In this case it is safe to use the Labeler but any attributes added to it will not be used.
type Option ¶
type Option interface {
// contains filtered or unexported methods
}
Option interface used for setting optional config properties.
func WithClientTrace ¶ added in v0.29.0
func WithClientTrace(f func(context.Context) *httptrace.ClientTrace) Option
WithClientTrace takes a function that returns client trace instance that will be applied to the requests sent through the otelhttp Transport.
func WithFilter ¶
WithFilter adds a filter to the list of filters used by the handler. If any filter indicates to exclude a request then the request will not be traced. All filters must allow a request to be traced for a Span to be created. If no filters are provided then all requests are traced. Filters will be invoked for each processed request, it is advised to make them simple and fast.
func WithMessageEvents ¶
WithMessageEvents configures the Handler to record the specified events (span.AddEvent) on spans. By default, no read or write events are recorded.
Valid events are:
- ReadEvents: Record a "read" span event after every http.Request.Body.Read.
- WriteEvents: Record a "write" span event after every http.ResponseWriter.Write.
The events do not include per-call byte-count attributes. Total request and response body sizes are recorded on the span according to HTTP semantic conventions.
func WithMeterProvider ¶
func WithMeterProvider(provider metric.MeterProvider) Option
WithMeterProvider specifies a meter provider to use for creating a meter. If none is specified, the global provider is used.
func WithMetricAttributesFn
deprecated
added in
v0.54.0
WithMetricAttributesFn returns an Option to set a function that maps an HTTP request to a slice of attribute.KeyValue. These attributes will be included in metrics for every request.
Deprecated: WithMetricAttributesFn is deprecated and will be removed in a future release. Use Labeler instead.
func WithPropagators ¶
func WithPropagators(ps propagation.TextMapPropagator) Option
WithPropagators configures specific propagators. If this option isn't specified, then the global TextMapPropagator is used.
func WithPublicEndpointFn ¶ added in v0.33.0
WithPublicEndpointFn runs with every request, and allows conditionally configuring the Handler to link the span with an incoming span context. If this option is not provided or returns false, then the association is a child association instead of a link.
func WithServerName ¶ added in v0.38.0
WithServerName returns an Option that sets the name of the (virtual) server handling requests.
func WithSpanNameFormatter ¶
WithSpanNameFormatter takes a function that will be called on every request and the returned string will become the Span Name.
When using http.ServeMux (or any middleware that sets the Pattern of http.Request), the span name formatter will run twice. Once when the span is created, and second time after the middleware, so the pattern can be used.
func WithSpanOptions ¶
func WithSpanOptions(opts ...trace.SpanStartOption) Option
WithSpanOptions configures an additional set of trace.SpanOptions, which are applied to each new span.
func WithTracerProvider ¶
func WithTracerProvider(provider trace.TracerProvider) Option
WithTracerProvider specifies a tracer provider to use for creating a tracer. If none is specified, the global provider is used.
type Transport ¶
type Transport struct {
// contains filtered or unexported fields
}
Transport implements the http.RoundTripper interface and wraps outbound HTTP(S) requests with a span and enriches it with metrics.
func NewTransport ¶
func NewTransport(base http.RoundTripper, opts ...Option) *Transport
NewTransport wraps the provided http.RoundTripper with one that starts a span, injects the span context into the outbound request headers, and enriches it with metrics.
If the provided http.RoundTripper is nil, http.DefaultTransport will be used as the base http.RoundTripper.
Example ¶
// Create an http.Client that uses the (ot)http.Transport
// wrapped around the http.DefaultTransport
_ = http.Client{
Transport: NewTransport(http.DefaultTransport),
}
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
example
module
|
|
|
Package filters provides a set of filters useful with the otelhttp.WithFilter() option to control which inbound requests are traced.
|
Package filters provides a set of filters useful with the otelhttp.WithFilter() option to control which inbound requests are traced. |
|
internal
|
|
|
request
Package request provides types and functionality to handle HTTP request handling.
|
Package request provides types and functionality to handle HTTP request handling. |
|
semconv
Package semconv provides OpenTelemetry semantic convention types and functionality.
|
Package semconv provides OpenTelemetry semantic convention types and functionality. |
|
semconv/test
module
|
|
|
test
module
|