go.opencensus.io: go.opencensus.io/plugin/ochttp Index | Examples | Files | Directories

package ochttp

import "go.opencensus.io/plugin/ochttp"

Package ochttp provides OpenCensus instrumentation for net/http package.

For server instrumentation, see Handler. For client-side instrumentation, see Transport.

Index

Examples

Package Files

client.go client_stats.go doc.go route.go server.go span_annotating_client_trace.go stats.go trace.go wrapped_body.go

Constants

const (
    HostAttribute       = "http.host"
    MethodAttribute     = "http.method"
    PathAttribute       = "http.path"
    URLAttribute        = "http.url"
    UserAgentAttribute  = "http.user_agent"
    StatusCodeAttribute = "http.status_code"
)

Attributes recorded on the span for the requests. Only trace exporters will need them.

Variables

var (
    // Deprecated: Use a Count aggregation over one of the other client measures to achieve the same effect.
    ClientRequestCount = stats.Int64(
        "opencensus.io/http/client/request_count",
        "Number of HTTP requests started",
        stats.UnitDimensionless)
    // Deprecated: Use ClientSentBytes.
    ClientRequestBytes = stats.Int64(
        "opencensus.io/http/client/request_bytes",
        "HTTP request body size if set as ContentLength (uncompressed)",
        stats.UnitBytes)
    // Deprecated: Use ClientReceivedBytes.
    ClientResponseBytes = stats.Int64(
        "opencensus.io/http/client/response_bytes",
        "HTTP response body size (uncompressed)",
        stats.UnitBytes)
    // Deprecated: Use ClientRoundtripLatency.
    ClientLatency = stats.Float64(
        "opencensus.io/http/client/latency",
        "End-to-end latency",
        stats.UnitMilliseconds)
)

Deprecated: client HTTP measures.

var (
    ClientSentBytes = stats.Int64(
        "opencensus.io/http/client/sent_bytes",
        "Total bytes sent in request body (not including headers)",
        stats.UnitBytes,
    )
    ClientReceivedBytes = stats.Int64(
        "opencensus.io/http/client/received_bytes",
        "Total bytes received in response bodies (not including headers but including error responses with bodies)",
        stats.UnitBytes,
    )
    ClientRoundtripLatency = stats.Float64(
        "opencensus.io/http/client/roundtrip_latency",
        "Time between first byte of request headers sent to last byte of response received, or terminal error",
        stats.UnitMilliseconds,
    )
)

The following client HTTP measures are supported for use in custom views.

var (
    ServerRequestCount = stats.Int64(
        "opencensus.io/http/server/request_count",
        "Number of HTTP requests started",
        stats.UnitDimensionless)
    ServerRequestBytes = stats.Int64(
        "opencensus.io/http/server/request_bytes",
        "HTTP request body size if set as ContentLength (uncompressed)",
        stats.UnitBytes)
    ServerResponseBytes = stats.Int64(
        "opencensus.io/http/server/response_bytes",
        "HTTP response body size (uncompressed)",
        stats.UnitBytes)
    ServerLatency = stats.Float64(
        "opencensus.io/http/server/latency",
        "End-to-end latency",
        stats.UnitMilliseconds)
)

The following server HTTP measures are supported for use in custom views:

var (
    // Host is the value of the HTTP Host header.
    //
    // The value of this tag can be controlled by the HTTP client, so you need
    // to watch out for potentially generating high-cardinality labels in your
    // metrics backend if you use this tag in views.
    Host, _ = tag.NewKey("http.host")

    // StatusCode is the numeric HTTP response status code,
    // or "error" if a transport error occurred and no status code was read.
    StatusCode, _ = tag.NewKey("http.status")

    // Path is the URL path (not including query string) in the request.
    //
    // The value of this tag can be controlled by the HTTP client, so you need
    // to watch out for potentially generating high-cardinality labels in your
    // metrics backend if you use this tag in views.
    Path, _ = tag.NewKey("http.path")

    // Method is the HTTP method of the request, capitalized (GET, POST, etc.).
    Method, _ = tag.NewKey("http.method")

    // KeyServerRoute is a low cardinality string representing the logical
    // handler of the request. This is usually the pattern registered on the a
    // ServeMux (or similar string).
    KeyServerRoute, _ = tag.NewKey("http_server_route")
)

The following tags are applied to stats recorded by this package. Host, Path and Method are applied to all measures. StatusCode is not applied to ClientRequestCount or ServerRequestCount, since it is recorded before the status is known.

var (
    // KeyClientMethod is the HTTP method, capitalized (i.e. GET, POST, PUT, DELETE, etc.).
    KeyClientMethod, _ = tag.NewKey("http_client_method")
    // KeyClientPath is the URL path (not including query string).
    KeyClientPath, _ = tag.NewKey("http_client_path")
    // KeyClientStatus is the HTTP status code as an integer (e.g. 200, 404, 500.), or "error" if no response status line was received.
    KeyClientStatus, _ = tag.NewKey("http_client_status")
    // KeyClientHost is the value of the request Host header.
    KeyClientHost, _ = tag.NewKey("http_client_host")
)

Client tag keys.

var (
    DefaultSizeDistribution    = view.Distribution(1024, 2048, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216, 67108864, 268435456, 1073741824, 4294967296)
    DefaultLatencyDistribution = view.Distribution(1, 2, 3, 4, 5, 6, 8, 10, 13, 16, 20, 25, 30, 40, 50, 65, 80, 100, 130, 160, 200, 250, 300, 400, 500, 650, 800, 1000, 2000, 5000, 10000, 20000, 50000, 100000)
)

Default distributions used by views in this package.

var (
    ClientSentBytesDistribution = &view.View{
        Name:        "opencensus.io/http/client/sent_bytes",
        Measure:     ClientSentBytes,
        Aggregation: DefaultSizeDistribution,
        Description: "Total bytes sent in request body (not including headers), by HTTP method and response status",
        TagKeys:     []tag.Key{KeyClientMethod, KeyClientStatus},
    }

    ClientReceivedBytesDistribution = &view.View{
        Name:        "opencensus.io/http/client/received_bytes",
        Measure:     ClientReceivedBytes,
        Aggregation: DefaultSizeDistribution,
        Description: "" /* 143 byte string literal not displayed */,
        TagKeys:     []tag.Key{KeyClientMethod, KeyClientStatus},
    }

    ClientRoundtripLatencyDistribution = &view.View{
        Name:        "opencensus.io/http/client/roundtrip_latency",
        Measure:     ClientRoundtripLatency,
        Aggregation: DefaultLatencyDistribution,
        Description: "End-to-end latency, by HTTP method and response status",
        TagKeys:     []tag.Key{KeyClientMethod, KeyClientStatus},
    }

    ClientCompletedCount = &view.View{
        Name:        "opencensus.io/http/client/completed_count",
        Measure:     ClientRoundtripLatency,
        Aggregation: view.Count(),
        Description: "Count of completed requests, by HTTP method and response status",
        TagKeys:     []tag.Key{KeyClientMethod, KeyClientStatus},
    }
)

Package ochttp provides some convenience views for client measures. You still need to register these views for data to actually be collected.

var (
    // Deprecated: No direct replacement, but see ClientCompletedCount.
    ClientRequestCountView = &view.View{
        Name:        "opencensus.io/http/client/request_count",
        Description: "Count of HTTP requests started",
        Measure:     ClientRequestCount,
        Aggregation: view.Count(),
    }

    // Deprecated: Use ClientSentBytesDistribution.
    ClientRequestBytesView = &view.View{
        Name:        "opencensus.io/http/client/request_bytes",
        Description: "Size distribution of HTTP request body",
        Measure:     ClientSentBytes,
        Aggregation: DefaultSizeDistribution,
    }

    // Deprecated: Use ClientReceivedBytesDistribution instead.
    ClientResponseBytesView = &view.View{
        Name:        "opencensus.io/http/client/response_bytes",
        Description: "Size distribution of HTTP response body",
        Measure:     ClientReceivedBytes,
        Aggregation: DefaultSizeDistribution,
    }

    // Deprecated: Use ClientRoundtripLatencyDistribution instead.
    ClientLatencyView = &view.View{
        Name:        "opencensus.io/http/client/latency",
        Description: "Latency distribution of HTTP requests",
        Measure:     ClientRoundtripLatency,
        Aggregation: DefaultLatencyDistribution,
    }

    // Deprecated: Use ClientCompletedCount instead.
    ClientRequestCountByMethod = &view.View{
        Name:        "opencensus.io/http/client/request_count_by_method",
        Description: "Client request count by HTTP method",
        TagKeys:     []tag.Key{Method},
        Measure:     ClientSentBytes,
        Aggregation: view.Count(),
    }

    // Deprecated: Use ClientCompletedCount instead.
    ClientResponseCountByStatusCode = &view.View{
        Name:        "opencensus.io/http/client/response_count_by_status_code",
        Description: "Client response count by status code",
        TagKeys:     []tag.Key{StatusCode},
        Measure:     ClientRoundtripLatency,
        Aggregation: view.Count(),
    }
)

Deprecated: Old client Views.

var (
    ServerRequestCountView = &view.View{
        Name:        "opencensus.io/http/server/request_count",
        Description: "Count of HTTP requests started",
        Measure:     ServerRequestCount,
        Aggregation: view.Count(),
    }

    ServerRequestBytesView = &view.View{
        Name:        "opencensus.io/http/server/request_bytes",
        Description: "Size distribution of HTTP request body",
        Measure:     ServerRequestBytes,
        Aggregation: DefaultSizeDistribution,
    }

    ServerResponseBytesView = &view.View{
        Name:        "opencensus.io/http/server/response_bytes",
        Description: "Size distribution of HTTP response body",
        Measure:     ServerResponseBytes,
        Aggregation: DefaultSizeDistribution,
    }

    ServerLatencyView = &view.View{
        Name:        "opencensus.io/http/server/latency",
        Description: "Latency distribution of HTTP requests",
        Measure:     ServerLatency,
        Aggregation: DefaultLatencyDistribution,
    }

    ServerRequestCountByMethod = &view.View{
        Name:        "opencensus.io/http/server/request_count_by_method",
        Description: "Server request count by HTTP method",
        TagKeys:     []tag.Key{Method},
        Measure:     ServerRequestCount,
        Aggregation: view.Count(),
    }

    ServerResponseCountByStatusCode = &view.View{
        Name:        "opencensus.io/http/server/response_count_by_status_code",
        Description: "Server response count by status code",
        TagKeys:     []tag.Key{StatusCode},
        Measure:     ServerLatency,
        Aggregation: view.Count(),
    }
)

Package ochttp provides some convenience views for server measures. You still need to register these views for data to actually be collected.

var DefaultClientViews = []*view.View{
    ClientRequestCountView,
    ClientRequestBytesView,
    ClientResponseBytesView,
    ClientLatencyView,
    ClientRequestCountByMethod,
    ClientResponseCountByStatusCode,
}

DefaultClientViews are the default client views provided by this package. Deprecated: No replacement. Register the views you would like individually.

var DefaultServerViews = []*view.View{
    ServerRequestCountView,
    ServerRequestBytesView,
    ServerResponseBytesView,
    ServerLatencyView,
    ServerRequestCountByMethod,
    ServerResponseCountByStatusCode,
}

DefaultServerViews are the default server views provided by this package. Deprecated: No replacement. Register the views you would like individually.

func NewSpanAnnotatingClientTrace Uses

func NewSpanAnnotatingClientTrace(_ *http.Request, s *trace.Span) *httptrace.ClientTrace

NewSpanAnnotatingClientTrace returns a httptrace.ClientTrace which annotates all emitted httptrace events on the provided Span.

func NewSpanAnnotator Uses

func NewSpanAnnotator(r *http.Request, s *trace.Span) *httptrace.ClientTrace

NewSpanAnnotator returns a httptrace.ClientTrace which annotates all emitted httptrace events on the provided Span. Deprecated: Use NewSpanAnnotatingClientTrace instead

func SetRoute Uses

func SetRoute(ctx context.Context, route string)

SetRoute sets the http_server_route tag to the given value. It's useful when an HTTP framework does not support the http.Handler interface and using WithRouteTag is not an option, but provides a way to hook into the request flow.

func TraceStatus Uses

func TraceStatus(httpStatusCode int, statusLine string) trace.Status

TraceStatus is a utility to convert the HTTP status code to a trace.Status that represents the outcome as closely as possible.

func WithRouteTag Uses

func WithRouteTag(handler http.Handler, route string) http.Handler

WithRouteTag returns an http.Handler that records stats with the http_server_route tag set to the given value.

type Handler Uses

type Handler struct {
    // Propagation defines how traces are propagated. If unspecified,
    // B3 propagation will be used.
    Propagation propagation.HTTPFormat

    // Handler is the handler used to handle the incoming request.
    Handler http.Handler

    // StartOptions are applied to the span started by this Handler around each
    // request.
    //
    // StartOptions.SpanKind will always be set to trace.SpanKindServer
    // for spans started by this transport.
    StartOptions trace.StartOptions

    // GetStartOptions allows to set start options per request. If set,
    // StartOptions is going to be ignored.
    GetStartOptions func(*http.Request) trace.StartOptions

    // IsPublicEndpoint should be set to true for publicly accessible HTTP(S)
    // servers. If true, any trace metadata set on the incoming request will
    // be added as a linked trace instead of being added as a parent of the
    // current trace.
    IsPublicEndpoint bool

    // FormatSpanName holds the function to use for generating the span name
    // from the information found in the incoming HTTP Request. By default the
    // name equals the URL Path.
    FormatSpanName func(*http.Request) string
}

Handler is an http.Handler wrapper to instrument your HTTP server with OpenCensus. It supports both stats and tracing.

Tracing

This handler is aware of the incoming request's span, reading it from request headers as configured using the Propagation field. The extracted span can be accessed from the incoming request's context.

span := trace.FromContext(r.Context())

The server span will be automatically ended at the end of ServeHTTP.

Code:

// import "go.opencensus.io/plugin/ochttp"

http.Handle("/users", ochttp.WithRouteTag(usersHandler, "/users"))

// If no handler is specified, the default mux is used.
log.Fatal(http.ListenAndServe("localhost:8080", &ochttp.Handler{}))

Code:

// import "go.opencensus.io/plugin/ochttp"

mux := http.NewServeMux()
mux.Handle("/users", ochttp.WithRouteTag(usersHandler, "/users"))
log.Fatal(http.ListenAndServe("localhost:8080", &ochttp.Handler{
    Handler:     mux,
    Propagation: &b3.HTTPFormat{},
}))

func (*Handler) ServeHTTP Uses

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

type Transport Uses

type Transport struct {
    // Base may be set to wrap another http.RoundTripper that does the actual
    // requests. By default http.DefaultTransport is used.
    //
    // If base HTTP roundtripper implements CancelRequest,
    // the returned round tripper will be cancelable.
    Base http.RoundTripper

    // Propagation defines how traces are propagated. If unspecified, a default
    // (currently B3 format) will be used.
    Propagation propagation.HTTPFormat

    // StartOptions are applied to the span started by this Transport around each
    // request.
    //
    // StartOptions.SpanKind will always be set to trace.SpanKindClient
    // for spans started by this transport.
    StartOptions trace.StartOptions

    // GetStartOptions allows to set start options per request. If set,
    // StartOptions is going to be ignored.
    GetStartOptions func(*http.Request) trace.StartOptions

    // NameFromRequest holds the function to use for generating the span name
    // from the information found in the outgoing HTTP Request. By default the
    // name equals the URL Path.
    FormatSpanName func(*http.Request) string

    // NewClientTrace may be set to a function allowing the current *trace.Span
    // to be annotated with HTTP request event information emitted by the
    // httptrace package.
    NewClientTrace func(*http.Request, *trace.Span) *httptrace.ClientTrace
}

Transport is an http.RoundTripper that instruments all outgoing requests with OpenCensus stats and tracing.

The zero value is intended to be a useful default, but for now it's recommended that you explicitly set Propagation, since the default for this may change.

Code:

// import (
// 		"go.opencensus.io/plugin/ochttp"
//		"go.opencensus.io/stats/view"
// )

if err := view.Register(
    // Register a few default views.
    ochttp.ClientSentBytesDistribution,
    ochttp.ClientReceivedBytesDistribution,
    ochttp.ClientRoundtripLatencyDistribution,
    // Register a custom view.
    &view.View{
        Name:        "httpclient_latency_by_path",
        TagKeys:     []tag.Key{ochttp.KeyClientPath},
        Measure:     ochttp.ClientRoundtripLatency,
        Aggregation: ochttp.DefaultLatencyDistribution,
    },
); err != nil {
    log.Fatal(err)
}

client := &http.Client{
    Transport: &ochttp.Transport{},
}

// Use client to perform requests.
_ = client

func (*Transport) CancelRequest Uses

func (t *Transport) CancelRequest(req *http.Request)

CancelRequest cancels an in-flight request by closing its connection.

func (*Transport) RoundTrip Uses

func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper, delegating to Base and recording stats and traces for the request.

Directories

PathSynopsis
propagation/b3Package b3 contains a propagation.HTTPFormat implementation for B3 propagation.
propagation/tracecontextPackage tracecontext contains HTTP propagator for TraceContext standard.

Package ochttp imports 15 packages (graph) and is imported by 77 packages. Updated 2019-04-25. Refresh now. Tools for package owners.