Documentation
¶
Index ¶
- Constants
- func ErrorType(code int, err error) string
- func NewMiddleware(serverName string) echo.MiddlewareFunc
- func NewMiddlewareWithConfig(config Config) echo.MiddlewareFunc
- func SpanNameFormatter(v Values) string
- func SpanStatus(code int, err error) (codes.Code, string)
- func SplitAddress(address string) (host string, port int, err error)
- type AttributesFunc
- type Config
- type MetricAttributesFunc
- type Metrics
- type MetricsRecorder
- type OnErrorFunc
- type RecordValues
- type Values
- func (v *Values) AppendMetricAttributes(attrs []attribute.KeyValue) []attribute.KeyValue
- func (v *Values) AppendSpanEndAttributes(attrs []attribute.KeyValue) []attribute.KeyValue
- func (v *Values) AppendStartAttributes(attrs []attribute.KeyValue) []attribute.KeyValue
- func (v *Values) ExtractRequest(r *http.Request) error
- func (v *Values) MetricAttributes() []attribute.KeyValue
- func (v *Values) SpanEndAttributes() []attribute.KeyValue
- func (v *Values) SpanStartAttributes() []attribute.KeyValue
Constants ¶
const ( // TracerKey is the key used to store the tracer in the echo context. TracerKey = "labstack-echo-otelecho-tracer" // ScopeName is the instrumentation scope name. ScopeName = "github.com/labstack/echo-otel/v5" )
const Version = "5.0.0"
Version is the current release version of the echo instrumentation.
Variables ¶
This section is empty.
Functions ¶
func ErrorType ¶
ErrorType returns the `error.type` attribute value for a server span and metrics, based on the resolved HTTP response status code and the error that occurred while handling the request. It returns an empty string when the request did not end with an error.
The request is considered to have ended with an error under the same rules as SpanStatus: a 5xx status code, an invalid status code, or an error alongside a 1xx-3xx status code. A 4xx status code is not an error for server spans.
The returned value is:
- the status code as a string (for example "500") for a 5xx status code when there is no error or the error carries an HTTP status code (implements `StatusCode() int`, like Echo v5's HTTPError),
- the error type for other errors, as returned by semconv.ErrorType: the value of an `ErrorType() string` method found in the error chain, otherwise the Go type of the error after unwrapping errors created with `fmt.Errorf("...: %w", err)` (for example "*net.OpError"). Errors joining several errors (`errors.Join`, `fmt.Errorf` with more than one `%w`) are not unwrapped and report their own type,
- the status code as a string for a status code above 599 without an error (net/http sends codes up to 999),
- "_OTHER" for a status code below 100 without an error.
The spec requires low cardinality. Error types are bounded by the code base, unless errors implement `ErrorType() string` with values that vary per request; avoid that, as error.type is also a metric attribute.
Spec:
If the request fails with an error before response status code was sent or received, error.type SHOULD be set to exception type (its fully-qualified class name, if applicable) or a component-specific low cardinality error identifier. If response status code was sent or received and status indicates an error according to HTTP span status definition, error.type SHOULD be set to the status code number (represented as a string), an exception type (if thrown) or a component-specific error identifier.
Reference: - [HTTP server span](https://opentelemetry.io/docs/specs/semconv/http/http-spans/#http-server-span) - [error.type](https://opentelemetry.io/docs/specs/semconv/registry/attributes/error/)
func NewMiddleware ¶
func NewMiddleware(serverName string) echo.MiddlewareFunc
NewMiddleware creates new echo opentelemetry middleware with the given server name.
func NewMiddlewareWithConfig ¶
func NewMiddlewareWithConfig(config Config) echo.MiddlewareFunc
NewMiddlewareWithConfig creates new echo opentelemetry middleware with the given configuration.
func SpanNameFormatter ¶
SpanNameFormatter returns the default format for the span name based on the HTTP method and path.
HTTP span names SHOULD be `{method} {target}` if there is a (low-cardinality) `target` available. If there is no (low-cardinality) `{target}` available, HTTP span names SHOULD be `{method}`.
The `{method}` MUST be `{http.request.method}` if the method represents the original method known to the instrumentation. In other cases (when `{http.request.method}` is set to `_OTHER`), `{method}` MUST be `HTTP`
Spec: https://opentelemetry.io/docs/specs/semconv/http/http-spans/#name
func SpanStatus ¶
SpanStatus returns the span status code and error description for a server span, based on the resolved HTTP response status code and the error that occurred while handling the request.
Spec:
Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, unless there was another error (e.g., network error receiving the response body; or 3xx codes with max redirects exceeded), in which case status MUST be set to Error. For HTTP status codes in the 4xx range span status MUST be left unset in case of SpanKind.SERVER and SHOULD be set to Error in case of SpanKind.CLIENT.
Reference: - [Span.Status](https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status) - [Recording errors on spans](https://opentelemetry.io/docs/specs/semconv/general/recording-errors/)
func SplitAddress ¶
SplitAddress splits server address or host into host (`server.address`) and port (`server.port`). Empty address is accepted and returns empty host and port. Port is part is not mandatory in address and can be omitted.
Types ¶
type AttributesFunc ¶
type AttributesFunc func(c *echo.Context, v *Values, attr []attribute.KeyValue) []attribute.KeyValue
AttributesFunc is used to extract additional attributes from the echo.Context and return them as a slice of attribute.KeyValue.
type Config ¶
type Config struct {
// ServerName is set as `server.address` and `server.port` span attributes. They are not added to metrics by
// default (Opt-In in the semantic conventions); add them with MetricAttributes if needed.
// Example: "api.example.com" or "example.com:8080". Without a port, `server.port` is not set.
//
// If known, this value must be set to the server’s canonical (primary) name.
// For example, in Apache this corresponds to the ServerName directive
// (https://httpd.apache.org/docs/2.4/mod/core.html#servername), and in NGINX
// to the server_name directive
// (http://nginx.org/en/docs/http/ngx_http_core_module.html#server_name).
//
// More generally, the primary server name is the host header value that maps
// to the HTTP server’s default virtual host. It must include the hostname,
// and if the server is accessed via a non-default port, the port must be
// appended using the standard ":port" suffix.
//
// If the primary server name is unknown, this field should be set to an
// empty string. In that case, Request.Host will be used to resolve the
// effective server name and port. Request.Host is chosen by the client.
ServerName string
// Skipper defines a function to skip middleware.
Skipper middleware.Skipper
// OnNextError is used to specify how errors returned from the next middleware / handler are handled.
OnNextError OnErrorFunc
// OnExtractionError is used to specify how errors returned from request extraction are handled.
OnExtractionError OnErrorFunc
// TracerProvider allows overriding the default tracer provider.
TracerProvider oteltrace.TracerProvider
// MeterProvider allows overriding the default meter provider.
MeterProvider metric.MeterProvider
// Propagators allow overriding the default propagators.
Propagators propagation.TextMapPropagator
// SpanStartOptions configures an additional set of trace.SpanStartOptions, which are applied to each new span.
SpanStartOptions []oteltrace.SpanStartOption
// SpanStartAttributes is used to extract additional attributes from the echo.Context
// and return them as a slice of attribute.KeyValue.
SpanStartAttributes AttributesFunc
// SpanEndAttributes is used to extract additional attributes from the echo.Context
// and return them as a slice of attribute.KeyValue.
SpanEndAttributes AttributesFunc
// MetricAttributes is used to compose attributes just before Metrics.Record call.
MetricAttributes MetricAttributesFunc
// Metrics is used to record custom metrics instead of default.
Metrics MetricsRecorder
}
Config is used to configure the middleware.
func (Config) ToMiddleware ¶
func (config Config) ToMiddleware() (echo.MiddlewareFunc, error)
ToMiddleware returns echo opentelemetry middleware which will trace incoming requests.
type MetricAttributesFunc ¶
MetricAttributesFunc is used to compose attributes for Metrics.Record.
type Metrics ¶
type Metrics struct {
// contains filtered or unexported fields
}
Metrics holds a standard set of OpenTelemetry global request/response metrics
func NewMetrics ¶
NewMetrics creates a new Metrics instance for Standard Required metric instances with the given Meter.
type MetricsRecorder ¶
type MetricsRecorder interface {
Record(c *echo.Context, v RecordValues)
}
MetricsRecorder is used to record metrics. This interface is used to allow custom metrics recording with access to the Echo context, so additional attributes can be extracted from it.
type OnErrorFunc ¶
OnErrorFunc is used to specify how errors are handled in the middleware.
type RecordValues ¶
type RecordValues struct {
// RequestDuration is the duration of request processing. Will be used with `http.server.request.duration` metric.
RequestDuration time.Duration
// ExtractedValues are values extracted from HTTP request and response before and after processing the next middleware/handler.
ExtractedValues Values
// Attributes are attributes to be used for recording metrics.
// If left empty, the Metrics.Record method will use default attributes by calling Values.MetricAttributes().
Attributes []attribute.KeyValue
}
RecordValues represents the values to Record metrics.
type Values ¶
type Values struct {
// HTTPMethod (`http.request.method`) - HTTP request method.
//
// If the HTTP request method is not known to instrumentation, it MUST set the `http.request.method` attribute to `_OTHER`
//
// If the HTTP instrumentation could end up converting valid HTTP request methods to `_OTHER`, then it MUST provide a
// way to override the list of known HTTP methods. If this override is done via environment variable, then the
// environment variable MUST be named `OTEL_INSTRUMENTATION_HTTP_KNOWN_METHODS` and support a comma-separated list of
// case-sensitive known HTTP methods (this list MUST be a full override of the default known method, it is not a
// list of known methods in addition to the defaults).
//
// HTTP method names are case-sensitive and `http.request.method` attribute value MUST match a known HTTP method name
// exactly. Instrumentations for specific web frameworks that consider HTTP methods to be case insensitive, SHOULD
// populate a canonical equivalent. Tracing instrumentations that do so, MUST also set `http.request.method_original`
// to the original value.
//
// Example: `GET`, `POST`, `_OTHER`
// Spec: https://opentelemetry.io/docs/specs/semconv/registry/attributes/http/
//
// Requirement Level:
// * span - Required
// * metric - Required
HTTPMethod string // metric, span
// HTTPMethodOriginal (`http.request.method_original`) is original HTTP method sent by the client in the request line.
// Example: `GeT`, `ACL`, `foo`
//
// Requirement Level:
// * span - conditionally required if raw value differs from `http.request.method` (different case) or `http.request.method` is `_OTHER`
// * metric - not used, as the value is chosen by the client and would make metric cardinality unbounded
HTTPMethodOriginal string // span
// ServerAddress (`server.address`) is the Name of the local HTTP server that received the request.
// This value can be provided by middleware configuration or extracted from `Request.Host` (together with ServerPort).
// Example values: `example.com` `10.1.2.80`, `/tmp/my.sock`
// See also: https://opentelemetry.io/docs/specs/semconv/http/http-spans/#setting-serveraddress-and-serverport-attributes
// Spec: https://opentelemetry.io/docs/specs/semconv/registry/attributes/server/
//
// Requirement Level:
// * span - Recommended
// * metric - Opt-In, not added by MetricAttributes as `Request.Host` is chosen by the client. Add it with a custom
// metric attributes function when the value comes from configuration.
ServerAddress string // span
// ServerPort (`server.port`) is the Port of the local HTTP server that received the request.
// This value can be provided by middleware configuration or extracted from `Request.Host` (only when ServerAddress
// is extracted from it too).
// Example values: `80` `8080`, `443`
// See also: https://opentelemetry.io/docs/specs/semconv/http/http-spans/#setting-serveraddress-and-serverport-attributes
// Spec: https://opentelemetry.io/docs/specs/semconv/registry/attributes/server/
//
// Requirement Level:
// * span - conditionally Required if available and `server.address` is set
// * metric - Opt-In, not added by MetricAttributes, same as ServerAddress
ServerPort int // span
// NetworkPeerAddress (`network.peer.address`) is peer address of the network connection - IP address or Unix domain socket name.
// Spec: https://opentelemetry.io/docs/specs/semconv/registry/attributes/network/
//
// Go: This value is derived from `Request.RemoteAddr` field value.
//
// Requirement Level:
// * span - Recommended
// * metric - not used
NetworkPeerAddress string // span (optional)
// NetworkPeerPort (`network.peer.port`) is peer port number of the network connection.
// Spec: https://opentelemetry.io/docs/specs/semconv/registry/attributes/network/
//
// Go: This value is derived from `Request.RemoteAddr` field value.
//
// Requirement Level:
// * span - Recommended if `network.peer.address` is set.
// * metric - not used
NetworkPeerPort int // span (optional)
// ClientAddress (`client.address`) is client address - domain name if available without reverse DNS lookup;
// otherwise, IP address or Unix domain socket name.
// Spec: https://opentelemetry.io/docs/specs/semconv/registry/attributes/client/
//
// Go: This value is derived by default from `Request.RemoteAddr` field value and is same as `network.peer.address`.
// The Echo middleware sets it from `Context.RealIP()`, which follows the Echo instance IP extraction settings
// (`Echo.IPExtractor`); headers like `X-Forwarded-For` are easy to spoof when they are trusted from any client.
//
// Requirement Level:
// * span - Recommended if `network.peer.address` is set.
// * metric - not used
ClientAddress string // span (optional)
// URLScheme (`url.scheme`) is the [URI scheme](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) component
// identifying the used protocol.
// The scheme of the original client request, if possible, from one of these headers:
// - [Forwarded#proto](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Forwarded#proto)
// - [X-Forwarded-Proto](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Forwarded-Proto)
// - Otherwise, the scheme of the immediate peer request.
// Example values: `http`, `https`
//
// Requirement Level:
// * span - Required
// * metric - Required
URLScheme string // metric, span
// URLPath (`url.path`) is the [URI](https://www.rfc-editor.org/rfc/rfc3986#section-3.3) path component.
// Spec: https://opentelemetry.io/docs/specs/semconv/registry/attributes/url/
//
// Go: This value is taken from `Request.URL.Path` method value.
//
// Requirement Level:
// * span - Required
// * metric - not used
URLPath string // span
// UserAgentOriginal (`user_agent.original`) is the value of the [HTTP User-Agent](https://www.rfc-editor.org/rfc/rfc9110.html#field.user-agent)
// header sent by the client.
// Spec: https://opentelemetry.io/docs/specs/semconv/registry/attributes/user-agent/
//
// Go: This value is taken from `Request.UserAgent()` method value.
//
// Requirement Level:
// * span - Recommended
// * metric - not used
UserAgentOriginal string // span
// NetworkProtocolName (`network.protocol.name`) is OSI application layer or non-OSI equivalent.
// Value is required if not value is not `http` and `network.protocol.version` value is set.
// The value SHOULD be normalized to lowercase.
// Example: `http`, `quic`, `spdy`
// Spec: https://opentelemetry.io/docs/specs/semconv/registry/attributes/network/
//
// Go: This value is derived from `Request.Proto` field value.
//
// Requirement Level:
// * span - conditionally Required if available and `network.protocol.version` is set
// * metric - conditionally Required if available and `network.protocol.version` is set
NetworkProtocolName string // metric, span
// NetworkProtocolVersion (`network.protocol.version`) is the actual version of the protocol used for network communication.
// Example: `1.0`, `1.1`, `2`, `3`
// Spec: https://opentelemetry.io/docs/specs/semconv/registry/attributes/network/
//
// Go: This value is derived from `Request.Proto` field value.
//
// Requirement Level:
// * span - Recommended
// * metric - Recommended
NetworkProtocolVersion string // metric, span
// HTTPRoute (`http.route`) is the matched route template for the request. This MUST be low-cardinality and include
// all static path segments, with dynamic path segments represented with placeholders.
// Spec: https://opentelemetry.io/docs/specs/semconv/registry/attributes/http/
//
// Go: The Echo middleware takes this value from `Context.Path()`, the matched Echo route. ExtractRequest uses the
// `Request.Pattern` field when the value is not set.
//
// Requirement Level:
// * span - Recommended
// * metric - Conditionally Required If and only if it's available
HTTPRoute string // metric, span
// HTTPRequestBodySize (`http.request.body.size`) is the size of the request payload body in bytes. This is the number
// of bytes transferred excluding headers and is often, but not always, present as the [Content-Length](https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length)
// header. For requests using transport encoding, this should be the compressed size.
// Spec: https://opentelemetry.io/docs/specs/semconv/http/http-metrics/#metric-httpserverrequestbodysize
//
// Go: This value is taken from `Request.ContentLength` and is negative (-1) if the size is unknown. Unknown size is
// not recorded.
//
// Requirement Level:
// * span - Opt-In, not added by SpanEndAttributes. Add it with a span end attributes function if needed.
// * metric - optional, is actual Histogram metric (`http.server.request.body.size`) and NOT attribute to metric.
HTTPRequestBodySize int64 // metric
// HTTPResponseStatusCode (`http.response.status_code`) is HTTP response status code.
// See also RFC: https://datatracker.ietf.org/doc/html/rfc7231#section-6
// Spec: https://opentelemetry.io/docs/specs/semconv/registry/attributes/http/
//
// Zero means no status was sent (for example the handler aborted the request); the attribute is not set then.
//
// Requirement Level:
// * span - conditionally Required if and only if one was received/sent
// * metric - conditionally Required if and only if one was received/sent
HTTPResponseStatusCode int // metric, span
// ErrorType (`error.type`) describes the class of error the request ended with. It is empty when the request did
// not end with an error. Use ErrorType function to determine the value.
// Spec: https://opentelemetry.io/docs/specs/semconv/registry/attributes/error/
//
// Requirement Level:
// * span - conditionally Required if request has ended with an error
// * metric - conditionally Required if request has ended with an error
ErrorType string // metric, span
// HTTPResponseBodySize (`http.response.body.size`) is the size of the response payload body in bytes. This is
// the number of bytes transferred excluding headers and is often, but not always, present as the
// [Content-Length](https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length) header. For requests using
// transport encoding, this should be the compressed size.
// Spec: https://opentelemetry.io/docs/specs/semconv/http/http-metrics/#metric-httpserverresponsebodysize
//
// Requirement Level:
// * span - Opt-In, not added by SpanEndAttributes. Add it with a span end attributes function if needed.
// * metric - optional, is actual Histogram metric (`http.server.response.body.size`) and NOT attribute to metric.
HTTPResponseBodySize int64 // metric
}
Values represent extracted values from HTTP request and response to be used for Span and Metrics attributes.
Span: Semantic Conventions for HTTP client and server spans. https://opentelemetry.io/docs/specs/semconv/http/http-spans/ Metrics: Semantic Conventions for HTTP client and server metrics. https://opentelemetry.io/docs/specs/semconv/http/http-metrics/
func (*Values) AppendMetricAttributes ¶
AppendMetricAttributes appends attributes for metric instruments from extracted values. Use this method instead of `MetricAttributes()` when you want to preallocate/reuse attributes slice. See also: https://opentelemetry.io/docs/specs/semconv/http/http-metrics/
func (*Values) AppendSpanEndAttributes ¶
AppendSpanEndAttributes appends attributes to be used when ending a span, after the next handler has been executed. Use this method instead of `SpanEndAttributes()` when you want to preallocate/reuse attributes slice.
func (*Values) AppendStartAttributes ¶
AppendStartAttributes appends attributes to be used when starting a span. Use this method instead of `SpanStartAttributes()` when you want to preallocate/reuse attributes slice.
func (*Values) ExtractRequest ¶
ExtractRequest extracts values from the given HTTP request and populates the Values struct.
func (*Values) MetricAttributes ¶
MetricAttributes creates attributes for metric instruments from extracted values.
Only low cardinality attributes are included: `http.request.method`, `url.scheme`, `http.route`, `network.protocol.name`, `network.protocol.version`, `http.response.status_code` and `error.type`. Opt-In attributes whose values the client chooses (`server.address` and `server.port` from `Request.Host`, `http.request.method_original`) are not included. See also: https://opentelemetry.io/docs/specs/semconv/http/http-metrics/
func (*Values) SpanEndAttributes ¶
SpanEndAttributes returns a list of attributes to be used when ending a span, after the next handler has been executed.
It adds `http.response.status_code` (if a status was sent) and `error.type` (if the request ended with an error). The Opt-In `http.request.body.size` and `http.response.body.size` attributes are not added.
func (*Values) SpanStartAttributes ¶
SpanStartAttributes returns a list of attributes to be used when starting a span.