Back to godoc.org

Package ochttp

v0.4.0
Latest Go to latest

The latest major version is .

Published: Mar 7, 2018 | License: Apache-2.0 | Module: go.opencensus.io

Overview

Package ochttp provides OpenCensus instrumentation for net/http package.

Index

Examples

Constants

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

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

Variables

var (
	ClientRequestCount, _  = stats.Int64("opencensus.io/http/client/request_count", "Number of HTTP requests started", stats.UnitNone)
	ClientRequestBytes, _  = stats.Int64("opencensus.io/http/client/request_bytes", "HTTP request body size if set as ContentLength (uncompressed)", stats.UnitBytes)
	ClientResponseBytes, _ = stats.Int64("opencensus.io/http/client/response_bytes", "HTTP response body size (uncompressed)", stats.UnitBytes)
	ClientLatency, _       = stats.Float64("opencensus.io/http/client/latency", "End-to-end latency", stats.UnitMilliseconds)
)

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

var (
	// Host is the value of the HTTP Host header.
	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.
	Path, _ = tag.NewKey("http.path")
	// Method is the HTTP method of the request, capitalized (GET, POST, etc.).
	Method, _ = tag.NewKey("http.method")
)

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, since it is recorded before the status is known.

var (
	DefaultSizeDistribution    = view.DistributionAggregation([]float64{0, 1024, 2048, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216, 67108864, 268435456, 1073741824, 4294967296})
	DefaultLatencyDistribution = view.DistributionAggregation([]float64{0, 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})
)
var (
	ClientRequestCountView = &view.View{
		Name:        "opencensus.io/http/client/request_count",
		Description: "Count of HTTP requests started",
		Measure:     ClientRequestCount,
		Aggregation: view.CountAggregation{},
	}

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

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

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

	ClientRequestCountByMethod = &view.View{
		Name:        "opencensus.io/http/client/request_count_by_method",
		Description: "Client request count by HTTP method",
		TagKeys:     []tag.Key{Method},
		Measure:     ClientRequestCount,
		Aggregation: view.CountAggregation{},
	}

	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:     ClientLatency,
		Aggregation: view.CountAggregation{},
	}

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

Package ochttp provides some convenience views. You need to subscribe to the views for data to actually be collected.

type Handler

type Handler struct {
	// NoStats may be set to disable recording of stats.
	NoStats bool

	// NoTrace may be set to disable recording of traces.
	NoTrace bool

	// 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
}

Handler is a http.Handler that is aware of the incoming request's span.

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.

Incoming propagation mechanism is determined by the given HTTP propagators.

Example

Code:

package main

import (
	"go.opencensus.io/plugin/ochttp"
	"log"
	"net/http"
)

var usersHandler http.Handler

func main() {
	// Enables OpenCensus for the default serve mux.
	// By default, B3 propagation is used.
	http.Handle("/users", usersHandler)
	log.Fatal(http.ListenAndServe("localhost:8080", &ochttp.Handler{}))
}
Example (Mux)

Code:

package main

import (
	"go.opencensus.io/plugin/ochttp"
	"go.opencensus.io/plugin/ochttp/propagation/google"
	"log"
	"net/http"
)

var usersHandler http.Handler

func main() {
	mux := http.NewServeMux()
	mux.Handle("/users", usersHandler)

	log.Fatal(http.ListenAndServe("localhost:8080", &ochttp.Handler{
		Handler:     mux,
		Propagation: &google.HTTPFormat{}, // Uses Google's propagation format.
	}))
}

func (*Handler) ServeHTTP

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

type Transport

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

	// NoStats may be set to disable recording of stats.
	NoStats bool

	// NoTrace may be set to disable recording of traces.
	NoTrace bool

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

	// Sampler if provided, will be consulted for each span generated by this
	// RoundTripper. Otherwise, the default sampling behavior takes place
	// (see trace.StartOptions).
	Sampler trace.Sampler
}

Transport is an http.RoundTripper that instruments all outgoing requests with stats and tracing. The zero value is intended to be a useful default, but for now it's recommended that you explicitly set Propagation.

Example

Code:

package main

import (
	"go.opencensus.io/plugin/ochttp"
	"go.opencensus.io/stats/view"
	"go.opencensus.io/tag"
	"log"
	"net/http"
)

func main() {
	err := view.Subscribe(
		// Subscribe to a few default views, with renaming
		ochttp.ClientRequestCountByMethod,
		ochttp.ClientResponseCountByStatusCode,
		ochttp.ClientLatencyView,
		// Subscribe to a custom view
		&view.View{
			Name:        "httpclient_latency_by_hostpath",
			TagKeys:     []tag.Key{ochttp.Host, ochttp.Path},
			Measure:     ochttp.ClientLatency,
			Aggregation: ochttp.DefaultLatencyDistribution,
		},
	)
	if err != nil {
		log.Fatal(err)
	}

	client := &http.Client{
		Transport: &ochttp.Transport{},
	}
	_ = client // use client to perform requests
}

func (*Transport) CancelRequest

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

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

func (*Transport) RoundTrip

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.

Package Files

Documentation was rendered with GOOS=linux and GOARCH=amd64.

Jump to identifier

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to identifier