telemetry

package
v0.54.2 Latest Latest
Warning

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

Go to latest
Published: Apr 15, 2026 License: Apache-2.0 Imports: 33 Imported by: 3,292

README

Quick Start For Local Telemetry

To quickly setup a local telemetry environment where OpenTelemetry data is sent to a local instance of Grafana LGTM:

start the Grafana LGTM docker image:

docker run -p 3000:3000 -p 4317:4317 -p 4318:4318 --rm -ti grafana/otel-lgtm

Environment Variable

Using the environment variable method will instantiate the OpenTelemetry SDK before global meters and spans. This allows meters and traces to use direct references to the underlying instrument.

Create a basic OpenTelemetry configuration file which will send data to the local instance of Grafana LGTM:

file_format: "1.0-rc.3"
resource:
  attributes:
    - name: service.name
      value: simapp

tracer_provider:
  processors:
    - batch: # NOTE: you should use batch in production!
        exporter:
          otlp_grpc:
            endpoint: http://localhost:4317

meter_provider:
  readers:
    - pull:
        exporter:
          prometheus/development: # pushes directly to prometheus backend. 
            host: 0.0.0.0
            port: 9464
            # optional: include resource attributes as constant labels
            with_resource_constant_labels:
              include:
                - service.name
  views:
    - selector:
        instrument_type: histogram
      stream:
        aggregation:
          explicit_bucket_histogram:
            boundaries: [ 0.2, 0.25, 0.3, 0.35, 0.4, 0.5, 0.75, 1, 2, 5 ]

logger_provider:
  processors:
    - batch:
        exporter:
          otlp_grpc:
            endpoint: http://localhost:4317


extensions:
  instruments:
    host: {} # enable optional host instrumentation with go.opentelemetry.io/contrib/instrumentation/host
    runtime: {} # enable optional runtime instrumentation with go.opentelemetry.io/contrib/instrumentation/runtime
    diskio: {} # enable optional disk I/O instrumentation using gopsutil
    # diskio with options:
    # diskio:
    #   disable_virtual_device_filter: true  # include virtual devices (loopback, RAID, partitions) on Linux
  propagators:
    - tracecontext

For a full list of configurable options see: https://github.com/open-telemetry/opentelemetry-configuration/blob/main/examples/kitchen-sink.yaml. NOTE: the go implementation may not support all options, so check the go otelconf documentation carefully to see what is actually supported.

  1. set the OTEL_EXPERIMENTAL_CONFIG_FILE environment variable to the path of the configuration file: export OTEL_EXPERIMENTAL_CONFIG_FILE=path/to/config.yaml
  2. start your application or tests
  3. view the data in Grafana LGTM at http://localhost:3000/. The Drilldown views are suggested for getting started.

Node Home OpenTelemetry file

The node's init command will generate an empty otel file in the ~/.<node_home>/config directory. Place your otel configuration here.

When the node's start command is run, the OpenTelemetry SDK will be initialized using this file. If left empty, all meters and tracers will be noop.

OpenTelemetry Initialization

While manual OpenTelemetry initialization is still supported, this package provides a single point of initialization such that end users can just use the official OpenTelemetry declarative configuration spec: https://opentelemetry.io/docs/languages/sdk-configuration/declarative-configuration/ End users only need to set the OTEL_EXPERIMENTAL_CONFIG_FILE environment variable to the path of an OpenTelemetry configuration file, or fill out the otel.yaml file in the node's config directory and that's it. All the documentation necessary is provided in the OpenTelemetry documentation.

Developer Usage

If using the environment variable method, importing the baseapp package will cause the telemetry's initialization to run. Otherwise, ensure the otel.yaml file in the node's config directory is filled out.

IMPORTANT: Make sure Shutdown() is called when the application is shutting down.

Tests can use the TestingMain function at startup to accomplish this.

If these steps are followed, developers can follow the official golang otel conventions of declaring package-level tracer and meter instances using otel.Tracer() and otel.Meter(). NOTE: it is important to thread context.Context properly for spans and metrics to be correlated correctly. When using the SDK's context type, spans must be started with Context.StartSpan to get an SDK context which has the span set correctly.

Documentation

Overview

Package telemetry initializes OpenTelemetry global using the OpenTelemetry declarative configuration API. It also provides some deprecated legacy metrics wrapper functions and metrics configuration using github.com/hashicorp/go-metrics. By default, this package configures the github.com/hashicorp/go-metrics default instance to send all metrics to OpenTelemetry. Existing users of the legacy wrapper functions in this package should begin to migrate their code to use OpenTelemetry APIs directly.

Index

Constants

View Source
const (
	// Deprecated: FormatDefault is the default format for metrics gathering.
	FormatDefault = ""
	// Deprecated: FormatPrometheus indicates Prometheus format for metrics gathering.
	FormatPrometheus = "prometheus"
	// Deprecated: FormatText indicates text format for metrics gathering.
	FormatText = "text"
	// Deprecated: ContentTypeText is the content type for text formatted metrics.
	ContentTypeText = `text/plain; version=` + expfmt.TextVersion + `; charset=utf-8`

	// Deprecated: MetricSinkInMem indicates in-memory metrics sink.
	MetricSinkInMem = "mem"
	// Deprecated: MetricSinkPrometheus indicates Prometheus metrics sink.
	MetricSinkStatsd = "statsd"
	// Deprecated: MetricSinkDogsStatsd indicates DogStatsD metrics sink.
	MetricSinkDogsStatsd = "dogstatsd"
	// Deprecated: MetricSinkOtel indicates OpenTelemetry metrics sink.
	MetricSinkOtel = "otel"
)

Metrics supported format types.

View Source
const (
	MetricKeyPreBlocker   = "pre_blocker"
	MetricKeyBeginBlocker = "begin_blocker"
	MetricKeyEndBlocker   = "end_blocker"
	MetricLabelNameModule = "module"
)

Common metric key constants

View Source
const (
	OtelFileName = "otel.yaml"
)

Variables

This section is empty.

Functions

func EnableTelemetry deprecated added in v0.53.0

func EnableTelemetry()

Deprecated: EnableTelemetry allows for the global telemetry enabled state to be set.

func IncrCounter deprecated

func IncrCounter(val float32, keys ...string)

Deprecated: IncrCounter provides a wrapper functionality for emitting a counter metric with global labels (if any).

func IncrCounterWithLabels deprecated

func IncrCounterWithLabels(keys []string, val float32, labels []metrics.Label)

Deprecated: IncrCounterWithLabels provides a wrapper functionality for emitting a counter metric with global labels (if any) along with the provided labels.

func InitializeOpenTelemetry added in v0.54.0

func InitializeOpenTelemetry(filePath string) error

InitializeOpenTelemetry initializes the OpenTelemetry SDK. We assume that the otel configuration file is in `~/.<your_node_home>/config/otel.yaml`. An empty otel.yaml is automatically placed in the directory above in the `appd init` command.

Note that a late initialization of the open telemetry SDK causes meters/tracers to utilize a delegate, which incurs an atomic load. In our benchmarks, we saw only a few nanoseconds incurred from this atomic operation. If you wish to avoid this overhead entirely, you may set the OTEL_EXPERIMENTAL_CONFIG_FILE environment variable,' and the OpenTelemetry SDK will be instantiated via init. This will eliminate the atomic operation overhead.

func IsOtelLoggerEnabled added in v0.54.0

func IsOtelLoggerEnabled() bool

IsOtelLoggerEnabled reports whether the global OTel log pipeline has active exporters. It returns false for the noop provider or any real provider with no log processors configured.

func IsTelemetryEnabled deprecated added in v0.50.6

func IsTelemetryEnabled() bool

Deprecated: IsTelemetryEnabled provides controlled access to check if telemetry is enabled.

func MeasureSince deprecated

func MeasureSince(start time.Time, keys ...string)

Deprecated: MeasureSince provides a wrapper functionality for emitting a time measure metric with global labels (if any).

func ModuleMeasureSince deprecated

func ModuleMeasureSince(module string, start time.Time, keys ...string)

Deprecated: ModuleMeasureSince provides a short hand method for emitting a time measure metric for a module with a given set of keys. If any global labels are defined, they will be added to the module label.

func ModuleSetGauge deprecated

func ModuleSetGauge(module string, val float32, keys ...string)

Deprecated: ModuleSetGauge provides a short hand method for emitting a gauge metric for a module with a given set of keys. If any global labels are defined, they will be added to the module label.

func NewLabel deprecated

func NewLabel(name, value string) metrics.Label

Deprecated: NewLabel creates a new instance of Label with name and value

func Now deprecated added in v0.50.6

func Now() time.Time

Deprecated: Now return the current time if telemetry is enabled or a zero time if it's not

func SetGauge deprecated

func SetGauge(val float32, keys ...string)

Deprecated: SetGauge provides a wrapper functionality for emitting a gauge metric with global labels (if any).

func SetGaugeWithLabels deprecated

func SetGaugeWithLabels(keys []string, val float32, labels []metrics.Label)

Deprecated: SetGaugeWithLabels provides a wrapper functionality for emitting a gauge metric with global labels (if any) along with the provided labels.

func Shutdown added in v0.54.0

func Shutdown(ctx context.Context) error

func TestingMain added in v0.54.0

func TestingMain(m *testing.M, ctx context.Context)

TestingMain should be used in tests where you want to run telemetry and need clean shutdown behavior at the end of the test, for instance to collect benchmark metrics. If ctx is nil, context.Background() is used. Example:

func TestMain(m *testing.M) {
    telemetry.TestingMain(m, nil)
}

Types

type Config deprecated

type Config struct {
	// Prefixed with keys to separate services
	ServiceName string `mapstructure:"service-name"`

	// Enabled enables the application telemetry functionality. When enabled,
	// an in-memory sink is also enabled by default. Operators may also enable
	// other sinks such as Prometheus.
	Enabled bool `mapstructure:"enabled"`

	// Enable prefixing gauge values with hostname
	EnableHostname bool `mapstructure:"enable-hostname"`

	// Enable adding hostname to labels
	EnableHostnameLabel bool `mapstructure:"enable-hostname-label"`

	// Enable adding service to labels
	EnableServiceLabel bool `mapstructure:"enable-service-label"`

	// PrometheusRetentionTime, when positive, enables a Prometheus metrics sink.
	// It defines the retention duration in seconds.
	PrometheusRetentionTime int64 `mapstructure:"prometheus-retention-time"`

	// GlobalLabels defines a global set of name/value label tuples applied to all
	// metrics emitted using the wrapper functions defined in telemetry package.
	//
	// Example:
	// [["chain_id", "cosmoshub-1"]]
	GlobalLabels [][]string `mapstructure:"global-labels"`

	// MetricsSink defines the type of metrics backend to use.
	// Can be one of "mem", "statsd", "dogstatsd", or "otel".
	MetricsSink string `mapstructure:"metrics-sink" default:"mem"`

	// StatsdAddr defines the address of a statsd server to send metrics to.
	// Only utilized if MetricsSink is set to "statsd" or "dogstatsd".
	StatsdAddr string `mapstructure:"statsd-addr"`

	// DatadogHostname defines the hostname to use when emitting metrics to
	// Datadog. Only utilized if MetricsSink is set to "dogstatsd".
	DatadogHostname string `mapstructure:"datadog-hostname"`
}

Config is the telemetry configuration.

Deprecated: Use OpenTelemetry instead.

type DisplayableSink deprecated added in v0.50.2

type DisplayableSink interface {
	DisplayMetrics(resp http.ResponseWriter, req *http.Request) (any, error)
}

DisplayableSink defines an interface for a sink to provide human-readable metrics.

Deprecated: DisplayableSink is an interface that defines a method for displaying metrics.

type ExtensionOptions added in v0.54.0

type ExtensionOptions struct {
	// TraceFile is an optional path to a file where spans should be exported
	// using the stdouttrace exporter. If empty, no file-based trace export is
	// configured.
	TraceFile string `json:"trace_file" yaml:"trace_file" mapstructure:"trace_file"`

	// MetricsFile is an optional path to a file where metrics should be written
	// using the stdoutmetric exporter. If unset, no file-based metrics export
	// is performed.
	MetricsFile string `json:"metrics_file" yaml:"metrics_file" mapstructure:"metrics_file"`

	// MetricsFileInterval defines how frequently metric data should be flushed
	// to MetricsFile. It must be a valid Go duration string (e.g. "10s",
	// "1m"). If empty, the default PeriodicReader interval is used.
	MetricsFileInterval string `json:"metrics_file_interval" yaml:"metrics_file_interval" mapstructure:"metrics_file_interval"`

	// LogsFile is an optional output file for structured logs exported through
	// the stdoutlog exporter. If unset, log exporting to file is disabled.
	LogsFile string `json:"logs_file" yaml:"logs_file" mapstructure:"logs_file"`

	// Instruments is a map of instrument names to their optional configuration.
	// Presence of a key enables the instrument. The value is an optional map of
	// instrument-specific settings. See each instrument package for available options.
	//
	// Example:
	//   instruments:
	//     host: {}
	//     runtime: {}
	//     diskio:
	//       disable_virtual_device_filter: true
	Instruments map[string]map[string]any `json:"instruments" yaml:"instruments" mapstructure:"instruments"`

	// Propagators configures additional or alternative TextMapPropagators
	// (e.g. "tracecontext", "baggage", "b3", "b3multi", "jaeger").
	Propagators []string `json:"propagators" yaml:"propagators" mapstructure:"propagators"`
}

ExtensionOptions provides configuration for OpenTelemetry features not yet supported by otelconf, such as writing traces/metrics/logs to local files, enabling additional host/runtime instrumentation, and configuring custom propagators.

When present in otel.yaml under the `extensions` key, these fields augment/override portions of the OpenTelemetry SDK initialization.

For an example configuration, see the README in this package.

type GatherResponse

type GatherResponse struct {
	Metrics     []byte
	ContentType string
}

GatherResponse is the response type of registered metrics

Depreacated: users should switch to OpenTelemetry.

type Metrics deprecated

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

Metrics defines a wrapper around application telemetry functionality. It allows metrics to be gathered at any point in time. When creating a Metrics object, internally, a global metrics is registered with a set of sinks as configured by the operator. In addition to the sinks, when a process gets a SIGUSR1, a dump of formatted recent metrics will be sent to STDERR.

Deprecated: users should switch to OpenTelemetry.

func New deprecated

func New(cfg Config) (_ *Metrics, rerr error)

New creates a new instance of Metrics

Deprecated: users should switch to OpenTelemetry.

func (*Metrics) Gather

func (m *Metrics) Gather(format string) (GatherResponse, error)

Gather collects all registered metrics and returns a GatherResponse where the metrics are encoded depending on the type. Metrics are either encoded via Prometheus or JSON if in-memory.

Directories

Path Synopsis
Package registry provides an instrument registry for telemetry instrumentation.
Package registry provides an instrument registry for telemetry instrumentation.
util
diskio
Package diskio provides an implementation of the disk I/O metrics following the OpenTelemetry semantic conventions for system metrics specified here: https://opentelemetry.io/docs/specs/semconv/system/system-metrics/.
Package diskio provides an implementation of the disk I/O metrics following the OpenTelemetry semantic conventions for system metrics specified here: https://opentelemetry.io/docs/specs/semconv/system/system-metrics/.
host
Package host provides a telemetry instrument wrapper for host-level metrics.
Package host provides a telemetry instrument wrapper for host-level metrics.
runtime
Package runtime provides a telemetry instrument wrapper for Go runtime metrics.
Package runtime provides a telemetry instrument wrapper for Go runtime metrics.

Jump to

Keyboard shortcuts

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