metrics

package
v0.3.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 3, 2024 License: MIT Imports: 45 Imported by: 118

README

Metrics Package

The metrics package contains standard drivers for opentracing, profiling and metrics.You can enable this in your appplication by calling metrics.Setup(). This will start the metric handler defined in the METRICS_HANDLER environment variable. The default is null which is a no-op handler.

METRICS_HANDLER env Description Supports Traces Supports Span Events Supports Profiling
OTLP OTLP Exporter protocol. Supported by various external providers including New Relic, Signoz, Grafana and more ❌ (but it can through pyroscope, by specifying the PYROSCOPE_ENDPOINT enviornment variable)
Jaeger Jaeger Client Clibrary, will soon be deprecated in favor of OTLP exports to jaeger as per this deprecation notice ❌ (but it can through pyroscope, by specifying the PYROSCOPE_ENDPOINT enviornment variable)

There's also a NAME_PREFIX environment variable that will prefix all the metrics with the value of NAME_PREFIX. This is useful for differentiating between different instances of the same service.

OTLP

We do our best to support enviornment variables specified in the Otel Spec and have added a few of our own. Key ones to note are:

Jaeger

Pass in the JAEGER_ENDPOINT enviornment variable

Pyroscope

Pass in the PYROSCOPE_ENDPOINT environment variable

Metrics Endpoint

The metrics endpoint is exposed on /metrics on port 8080 by default and is compatible with prometheus. The following options control the metrics endpoint:

Enviornment Variable Description Default
METRICS_PORT_ENABLED Wether or not to enable the metrics endpoint. true
METRICS_PORT Port to serve metrics on. 8080
METRICS_PATH Path to serve metrics on /metrics
METRICS_ALWAYS_SYNC Wether or not to wait until metrics have been exported before ending a span false

Note: this server failing to bind to METRICS_PORT will not cause the application to fail to start. The error will be logged.

Logger

Currently, the entire sanguine codebase uses ipfs go-log. As pointed out in #1521, this is not a good long term solution since the logs are not currently appended to opentelemetry, and so new traces require telemtry.

In an attempt to fix this, we introduced the new context aware otelzap logger. Since this is in beta, you ned to call handler.ExperimentalLogger. In a future version, we will remove the handler.ExperimentalLogger and replace it with handler.Logger and deprecate ipfs/go-log.

The current logger is currently depended on by a large amount of modules:

image so it'd be wise to keep this module out of new code until ready to do an entire go.module, and possibly it's dependencies. This should be tracked in #1521

Limitations

Currently, no enviornment variables are supported for the logger. This is a known limitation and will be fixed in a future release. Things like controlling the log level, sugarring, format, etc are not currently supported. These will be added as the module beocmes more stable.

Note: because both ipfs go-log and otelzap logger depend on zap globals, in orderr to enable globals you can set ENABLE_EXPERIMENTAL_ZAP_GLOBALS to true in your environment. This will enable the zap globals, and you can use the handler.Logger to log to the global logger. This is not recommended, and will be removed in a future release.

Using the logger

Since the logger is dependent on the context to derive the current span, you need to always use logger.Ctx(ctx) or logger.InfoCtx. One thing under consideration is removing the non-ctx methods

Documentation

Overview

Package metrics implements a metrics dashboard with either

Index

Constants

View Source
const (
	// MetricsPortEnabledEnv is the environment variable that controls whether the metrics server is enabled.
	MetricsPortEnabledEnv = "METRICS_PORT_ENABLED"

	// MetricsPath is the environment variable that controls the path for the metrics server.
	MetricsPath = "METRICS_PATH"

	// MetricsPathDefault is the default path for the metrics server.
	MetricsPathDefault = "/metrics"
)
View Source
const (
	// ChainID is the metric name for the chain ID.
	ChainID = "chain_id"
	// EOAAddress is the metric name for an eoa address.
	EOAAddress = "eoa_address"
	// ContractAddress is the metric name for the contract address.
	ContractAddress = "contract_address"
	// Origin is the metric name for the origin chain ID.
	Origin = "origin_chain_id"
	// Destination is the metric name for the destination chain ID.
	Destination = "destination_chain_id"
	// Nonce is the metric name for the nonce.
	Nonce = "nonce"
	// TxHash is the metric name for the transaction hash.
	TxHash = "tx_hash"
	// BlockHash is the metric name for the block hash.
	BlockHash = "block_hash"
	// FromBlock is the metric name for the block number.
	FromBlock = "from_block"
	// ToBlock is the metric name for the to block.
	ToBlock = "to_block"
	// Page is the metric name for the page.
	Page = "page"
	// Contract is the metric name for the contract.
	Contract = "contract"
	// MessageExecuted is the metric name for the message executed.
	MessageExecuted = "message_executed"
)
View Source
const HandlerEnv = "METRICS_HANDLER"

HandlerEnv is the driver to use for metrics.

Variables

View Source
var AllHandlerTypes []HandlerType

AllHandlerTypes is a list of all contract types. Since we use stringer and this is a testing library, instead of manually copying all these out we pull the names out of stringer. In order to make sure stringer is updated, we panic on any method called where the index is higher than the stringer array length.

Functions

func EndSpan added in v0.0.43

func EndSpan(span trace.Span)

EndSpan ends a span.

func EndSpanWithErr added in v0.0.43

func EndSpanWithErr(span trace.Span, err error)

EndSpanWithErr ends a span and records an error if one is present.

func PyroscopeWrapTracerProvider added in v0.0.43

func PyroscopeWrapTracerProvider(provider trace.TracerProvider, buildInfo config.BuildInfo, extraOpts ...otelpyroscope.Option) trace.TracerProvider

PyroscopeWrapTracerProvider wraps the tracer provider with pyroscope. The traceProvider is not affected if the pyroscope endpoint is not set.

func RPCClient added in v0.0.43

func RPCClient(ctx context.Context, metrics Handler, url string, client *http.Client, opts ...otelhttp.Option) (*rpc.Client, error)

RPCClient is a wrapper around rpc.Client that adds metrics/tracing.

func Setup added in v0.0.19

func Setup(ctx context.Context, buildInfo config.BuildInfo) error

Setup sets up the global metrics handler. In general, we discourage globals but because of the ubiquitiy of global variables and the tangential nature of metrics, we allow this.

func StartPyroscope added in v0.0.43

func StartPyroscope(info config.BuildInfo) *pyroscope.Profiler

StartPyroscope starts the pyroscope profiler. this will not run if the pyroscope endpoint is not set.

Types

type Handler added in v0.0.19

type Handler interface {
	Start(ctx context.Context) error
	// Gin gets a gin middleware for tracing.
	Gin() gin.HandlerFunc
	// ConfigureHTTPClient configures tracing on an http client
	ConfigureHTTPClient(client *http.Client, opts ...otelhttp.Option)
	// AddGormCallbacks adds gorm callbacks for tracing.
	AddGormCallbacks(db *gorm.DB)
	// GetTracerProvider returns the tracer provider.
	GetTracerProvider() trace.TracerProvider
	// Tracer returns the tracer provider.
	Tracer() trace.Tracer
	// Propagator returns the propagator.
	Propagator() propagation.TextMapPropagator
	// Type returns the handler type.
	Type() HandlerType
	// Metrics returns a metric provider
	// Deprecated: Will be removed in a future version please use meter.
	Metrics() Meter
	// Meter returns a metric provider
	Meter(name string, options ...metric.MeterOption) metric.Meter
	// Handler returns the http handler for the metrics endpoint.
	// right now, this supports only a single route
	Handler() http.Handler
	// ExperimentalLogger returns an experimental logger.
	ExperimentalLogger() experimentalLogger.ExperimentalLogger
}

Handler collects metrics.

func Get added in v0.0.19

func Get() Handler

Get gets the global handler.

func NewByType added in v0.0.43

func NewByType(ctx context.Context, buildInfo config.BuildInfo, ht HandlerType) (handler Handler, err error)

NewByType sets up a metrics handler by type.

func NewFromEnv added in v0.0.19

func NewFromEnv(ctx context.Context, buildInfo config.BuildInfo) (handler Handler, err error)

NewFromEnv sets up a metrics handler from environment variable. this will not set the global and generally, SetupFromEnv should be used instead.

func NewJaegerHandler added in v0.0.43

func NewJaegerHandler(buildInfo config.BuildInfo) Handler

NewJaegerHandler creates a new jaeger handler for handling jaeger traces. the JAEGER_ENDPOINT environment variable must be set for this to work. Note: currently, this is only suitable for local runs, because of default options we've put in place This can be fixed in a future version through an option builder. TODO: this should be replaced w/ the otlp exporter.

func NewNullHandler added in v0.0.19

func NewNullHandler() Handler

NewNullHandler creates a new null transaction handler.

func NewOTLPMetricsHandler added in v0.0.60

func NewOTLPMetricsHandler(buildInfo config.BuildInfo) Handler

NewOTLPMetricsHandler creates a new newrelic metrics handler.

type HandlerType added in v0.0.19

type HandlerType uint8

HandlerType is the handler type to use

const (
	// OTLP is the otlp driver.
	OTLP HandlerType = iota + 1 // OTLP
	// Jaeger is the jaeger driver.
	Jaeger // Jaeger
	// Null is a null data type handler.
	Null // Null
)

func (HandlerType) Lower added in v0.0.19

func (i HandlerType) Lower() string

Lower gets the lowercase version of the handler type. Useful for comparison in switch.

func (HandlerType) String added in v0.0.19

func (i HandlerType) String() string

type Meter added in v0.0.63

type Meter interface {
	// NewCounter creates a new meter counter instrument.
	NewCounter(meterName string, counterName string, desc string, units string) (metric.Int64Counter, error)
	// NewHistogram creates a new meter histogram instrument.
	NewHistogram(meterName string, histName string, desc string, units string) (metric.Int64Histogram, error)
}

Meter is an interface for counter and histogram. Deprecated: will be removed in a future version.

type MeterImpl added in v0.0.63

type MeterImpl struct {
	// contains filtered or unexported fields
}

MeterImpl is an implementation of the MeterProvider interface.

func NewOtelMeter added in v0.0.63

func NewOtelMeter(mp MeterProvider) *MeterImpl

NewOtelMeter creates a new meter provider. Deprecated: will be removed in a future version.

func (*MeterImpl) NewCounter added in v0.0.63

func (m *MeterImpl) NewCounter(meterName string, counterName string, desc string, units string) (metric.Int64Counter, error)

NewCounter creates a new meter counter instrument. https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/api.md#counter Deprecated: will be removed in a future version.

func (*MeterImpl) NewHistogram added in v0.0.63

func (m *MeterImpl) NewHistogram(meterName string, histName string, desc string, units string) (metric.Int64Histogram, error)

NewHistogram creates a new meter histogram instrument. https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/api.md#histogram Deprecated: will be removed in a future version.

type MeterProvider added in v0.0.66

type MeterProvider interface {
	metric.MeterProvider
	// Shutdown shuts down the MeterProvider flushing all pending telemetry and
	// releasing any held computational resources.
	//
	// This call is idempotent. The first call will perform all flush and
	// releasing operations. Subsequent calls will perform no action and will
	// return an error stating this.
	//
	// Measurements made by instruments from meters this MeterProvider created
	// will not be exported after Shutdown is called.
	//
	// This method honors the deadline or cancellation of ctx. An appropriate
	// error will be returned in these situations. There is no guaranteed that all
	// telemetry be flushed or all resources have been released in these
	// situations.
	//
	// This method is safe to call concurrently.
	Shutdown(ctx context.Context) error
	// ForceFlush flushes all pending telemetry.
	//
	// This method honors the deadline or cancellation of ctx. An appropriate
	// error will be returned in these situations. There is no guaranteed that all
	// telemetry be flushed or all resources have been released in these
	// situations.
	//
	// This method is safe to call concurrently.
	ForceFlush(ctx context.Context) error
}

MeterProvider is an interface for creating and registering meters. It also allows the provider to be managed.

type NullCounter added in v0.0.63

type NullCounter struct {
	embedded.Int64Counter
}

NullCounter is a no-op implementation of the metric.Int64Counter.

func (*NullCounter) Add added in v0.0.63

func (n *NullCounter) Add(_ context.Context, _ int64, _ ...metric.AddOption)

Add is a no-op implementation of Int64Counter Add() function.

type NullHistogram added in v0.0.63

type NullHistogram struct {
	embedded.Int64Histogram
}

NullHistogram is a no-op implementation of the metric.Int64Histogram.

func (*NullHistogram) Record added in v0.0.63

func (n *NullHistogram) Record(_ context.Context, _ int64, _ ...metric.RecordOption)

Record is a no-op implementation of RecordOption Record() function.

type NullMeterImpl added in v0.0.63

type NullMeterImpl struct{}

NullMeterImpl is a no-op implementation of the Meter interface. Deprecated: will be removed in a future version.

func (*NullMeterImpl) Meter added in v0.0.66

func (m *NullMeterImpl) Meter() metric.Meter

Meter providees a no-op implementation of the Meter interface.

func (*NullMeterImpl) NewCounter added in v0.0.63

func (m *NullMeterImpl) NewCounter(_ string, _ string, _ string, _ string) (metric.Int64Counter, error)

NewCounter creates a new meter counter instrument.

func (*NullMeterImpl) NewHistogram added in v0.0.63

func (m *NullMeterImpl) NewHistogram(_ string, _ string, _ string, _ string) (metric.Int64Histogram, error)

NewHistogram creates a new meter histogram instrument.

type TestHandler added in v0.0.43

type TestHandler interface {
	Handler
	// GetSpansByName returns all spans with the given name.
	GetSpansByName(name string) (spans []tracetest.SpanStub)
}

TestHandler is a handler that can be used for testing traces.

func NewTestTracer added in v0.0.43

func NewTestTracer(ctx context.Context, tb testing.TB) TestHandler

NewTestTracer returns a new test tracer.

Directories

Path Synopsis
Package instrumentation provides a set of custom instruments for different providers.
Package instrumentation provides a set of custom instruments for different providers.
Package internal contains internal constants for metrics package this is done in a separate package to avoid circular dependencies
Package internal contains internal constants for metrics package this is done in a separate package to avoid circular dependencies
Package localmetrics provides a local server for metrics.
Package localmetrics provides a local server for metrics.
Package logger provides a logger interface and a null logger implementation.
Package logger provides a logger interface and a null logger implementation.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL