Documentation
¶
Overview ¶
Package touchhttp defines the HTTP-specific behavior for metrics within an uber/fx app which uses the touchstone package.
Bootstrapping is similar to touchstone: A Config object can be available in the enclosing fx.App that will tailor certain aspects of the metrics http.Handler.
ServerBundle and ClientBundle are prebaked, opinionated metrics for instrumenting HTTP servers and clients. They each produce middleware given a label for a particular server or client.
Example ¶
/*
_ = fx.New(
fx.Logger(log.New(ioutil.Discard, "", 0)),
touchstone.Provide(),
Provide(),
fx.Provide(
func(sb ServerBundle) func(http.Handler) http.Handler { // can use justinas/alice
return sb.ForServer("main").Then
},
func(middleware func(http.Handler) http.Handler) http.Handler {
return middleware(
http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
fmt.Println("handled!")
}),
)
},
),
fx.Invoke(
func(h http.Handler) {
h.ServeHTTP(
httptest.NewRecorder(),
httptest.NewRequest("GET", "/", nil),
)
},
),
)
// Output:
// handled!
*/
Index ¶
- Constants
- Variables
- func NewHandlerOpts(cfg Config, p fx.Printer, r prometheus.Registerer) (opts promhttp.HandlerOpts, err error)
- func Provide() fx.Option
- type ClientBundle
- type ClientInstrumenter
- type Config
- type ErrorPrinter
- type Handler
- type In
- type InvalidErrorHandlingError
- type Labels
- type ServerBundle
- type ServerInstrumenter
Examples ¶
Constants ¶
const ( // DefaultServerCount is the default name of the counter that tracks the // total number of received server requests. DefaultServerCount = "server_request_count" // DefaultServerDuration is the default name of the observer that tracks // the total time taken by handlers to process requests. DefaultServerDuration = "server_request_duration_ms" // DefaultServerInFlight is the default name of the gauge that tracks the // instantaneous view of how many requests the handler is currently serving. DefaultServerInFlight = "server_requests_in_flight" // DefaultServerRequestSize is the default name of the observer that tracks the sizes // of requests received by handlers. DefaultServerRequestSize = "server_request_size" // DefaultClientCount is the default name of the counter that tracks the // total number of outgoing server requests. DefaultClientCount = "client_request_count" // DefaultClientDuration is the default name of the observer that tracks // the total time taken to send a request and receive a response. DefaultClientDuration = "client_request_duration_ms" // DefaultClientInFlight is the default name of the gauge that tracks the // instantaneous view of how many requests the client has currently pending. DefaultClientInFlight = "client_requests_in_flight" // DefaultClientRequestSize is the default name of the observer that tracks the sizes // of requests sent to servers. DefaultClientRequestSize = "client_request_size" // DefaultClientErrorCount is the default name of the count of total number of errors // (nil responses) that occurred since startup. DefaultClientErrorCount = "client_error_count" )
const ( // HTTPErrorOnError is the value allowed for Config.ErrorHandling that maps // to promhttp.HTTPErrorOnError. This is also the default used when no // value is set. HTTPErrorOnError = "http" // ContinueOnError is the value allowed for Config.ErrorHandler that maps // to promhttp.ContinueOnError. ContinueOnError = "continue" // PanicOnError is the value allowed for Config.ErrorHandler that maps // to promhttp.PanicOnError. PanicOnError = "panic" )
const ( // CodeLabel is the metric label containing the HTTP response code. CodeLabel = "code" // MethodLabel is the metric label containing the HTTP request's method. MethodLabel = "method" // ServerLabel is the canonical metric label name containing the name of the HTTP server. // This label is not automatically supplied. ServerLabel = "server" // ClientLabel is the canonical metric label name containing the name of the HTTP client. // This label is not automatically supplied. ClientLabel = "client" // MethodUnrecognized is used when an HTTP method is not one of the // standard methods, as enumerated in the net/http package. MethodUnrecognized = "UNRECOGNIZED" )
Variables ¶
var ( // ErrReservedLabelName indicates that labels supplied to build an instrumenter // had one or more reserved label names. ErrReservedLabelName = fmt.Errorf( "%s and %s are reserved label names and are supplied automatically", CodeLabel, MethodLabel, ) )
Functions ¶
func NewHandlerOpts ¶
func NewHandlerOpts(cfg Config, p fx.Printer, r prometheus.Registerer) (opts promhttp.HandlerOpts, err error)
NewHandlerOpts creates a basic HandlerOpts from an Config configuration.
func Provide ¶
Provide bootstraps the promhttp environment for an uber/fx app. This function creates the following component types:
- promhttp.HandlerOpts
- touchhttp.Handler This is the http.Handler to use to serve prometheus metrics. It will be instrumented if Config.InstrumentMetricHandler is set to true.
Types ¶
type ClientBundle ¶
type ClientBundle struct {
// Count describes the options used for the total request counter
Count prometheus.CounterOpts
// InFlight describes the options used for the instaneous request gauge
InFlight prometheus.GaugeOpts
// RequestSize describes the options for the request size observer. A panic
// will result if this field is not nil, a prometheus.HistogramOpts, or
// a prometheus.SummaryOpts.
RequestSize interface{}
// Duration describes the options for the request duration observer. A panic
// will result if this field is not either a prometheus.HistogramOpts or a prometheus.SummaryOpts.
Duration interface{}
// ErrorCount describes the options for the error counter.
ErrorCount prometheus.CounterOpts
// Now is the strategy for extracting the current system time. If unset,
// time.Now is used.
Now func() time.Time
}
func (ClientBundle) ForClient ¶
func (cb ClientBundle) ForClient(f *touchstone.Factory, l prometheus.Labels) (ci ClientInstrumenter, err error)
ForClient produces a ClientInstrumenter using this bundle of metric options. The internal server defaults are applied to each option for fields that are unset, e.g. metric names.
This method may be called multiple times with different prometheus.Labels. In that case each call must supply the same label names, or the underlying prometheus library will return an error.
type ClientInstrumenter ¶
type ClientInstrumenter struct {
// contains filtered or unexported fields
}
ClientInstrumenter is a clientside middleware that provides HTTP client metrics.
type Config ¶
type Config struct {
// ErrorHandling is the promhttp.HandlerErrorHandling value. If this field
// is unset, promhttp.HTTPErrorOnError is used.
//
// See: https://pkg.go.dev/github.com/prometheus/client_golang/prometheus/promhttp#HandlerErrorHandling
ErrorHandling string `json:"errorHandling" yaml:"errorHandling"`
// DisableCompression disables compression on metrics output.
DisableCompression bool `json:"disableCompression" yaml:"disableCompression"`
// MaxRequestsInFlight controls the number of concurrent HTTP metrics requests.
MaxRequestsInFlight int `json:"maxRequestsInFlight" yaml:"maxRequestsInFlight"`
// Timeout is the time period after which the handler will return a 503.
Timeout time.Duration `json:"timeout" yaml:"timeout"`
// EnableOpenMetrics controls whether open metrics encoding is available
// during content negotiation.
EnableOpenMetrics bool `json:"enableOpenMetrics" yaml:"enableOpenMetrics"`
// InstrumentMetricHandler indicates whether the http.Handler that renders
// prometheus metrics will itself be decorated with metrics.
//
// See: https://pkg.go.dev/github.com/prometheus/client_golang/prometheus/promhttp#InstrumentMetricHandler
InstrumentMetricHandler bool `json:"instrumentMetricHandler" yaml:"instrumentMetricHandler"`
}
Config is the configuration for boostrapping the promhttp package.
type ErrorPrinter ¶
ErrorPrinter adapts an fx.Printer and allows it to be used as an error Logger for prometheus.
func (ErrorPrinter) Println ¶
func (ep ErrorPrinter) Println(values ...interface{})
Println satisfies the promhttp.Logger interface.
type Handler ¶
Handler is a type alias for http.Handler that makes dependency injection easier. The handler bootstrapped by this package will be of this type, which means injection by type will not interfere with any other http.Handler component in the application.
The promhttp.HandlerFor function is used to create this type using the handler options created from the Config type.
See: https://pkg.go.dev/github.com/prometheus/client_golang/prometheus/promhttp#HandlerFor
type In ¶
type In struct {
fx.In
// Config is the prometheus configuration. This is optional,
// as a zero value for Config will result in a default environment.
Config Config `optional:"true"`
// Printer is the fx.Printer to which this package writes messages.
// This is optional, and if unset no messages are written.
Printer fx.Printer `optional:"true"`
// Now is the optional current time function. If supplied, this
// will be used for computing metric durations.
Now func() time.Time `optional:"true"`
}
In represents the components used by this package to bootstrap a promhttp environment. Provide uses these components.
type InvalidErrorHandlingError ¶
type InvalidErrorHandlingError struct {
// Value is the unrecognized Config.ErrorHandling value.
Value string
}
InvalidErrorHandlingError is the error returned when Config.ErrorHandling is not a recognized value.
func (*InvalidErrorHandlingError) Error ¶
func (e *InvalidErrorHandlingError) Error() string
Error satisfies the error interface.
type Labels ¶ added in v0.1.0
type Labels prometheus.Labels
Labels is a convenient extension for a prometheus.Labels that adds support for the reserved and de facto labels in this package.
The zero value for this map is usable with any of its methods.
func NewLabels ¶ added in v0.1.0
NewLabels creates a touchhttp Labels with code and method set appropriately.
func (*Labels) SetClient ¶ added in v0.1.0
SetClient updates this set of Labels with the given client name.
func (*Labels) SetCode ¶ added in v0.1.0
SetCode updates this set of Labels with the given HTTP status code Passing a value outside the range of valid HTTP response code values (e.g. zero) means http.StatusOK.
type ServerBundle ¶
type ServerBundle struct {
// Count describes the options used for the total request counter
Count prometheus.CounterOpts
// InFlight describes the options used for the instaneous request gauge
InFlight prometheus.GaugeOpts
// RequestSize describes the options for the request size observer. A panic
// will result if this field is not nil, a prometheus.HistogramOpts, or
// a prometheus.SummaryOpts.
RequestSize interface{}
// Duration describes the options for the request duration observer. A panic
// will result if this field is not nil, a prometheus.HistogramOpts, or
// a prometheus.SummaryOpts.
Duration interface{}
// Now is the strategy for extracting the current system time. If unset,
// time.Now is used.
Now func() time.Time
}
func (ServerBundle) ForServer ¶
func (sb ServerBundle) ForServer(f *touchstone.Factory, l prometheus.Labels) (si ServerInstrumenter, err error)
ForServer produces a ServerInstrumenter using this bundle of metric options. The internal server defaults are applied to each option for fields that are unset, e.g. metric names.
This method may be called multiple times with different prometheus.Labels. In that case each call must supply the same label names, or the underlying prometheus library will return an error.
type ServerInstrumenter ¶
type ServerInstrumenter struct {
// contains filtered or unexported fields
}
ServerInstrumenter is a serverside middleware that provides http.Handler metrics.