Skip to main content

Metrics library

This repo contains a metrics library implemented in Go and Python. The goal of the library is to be transparent inside the deployment: if metrics are disabled, the application code does not change.

Installation

Python

pip install spacearth-metrics

Go

go get github.com/Spacearth-NAV/metrics-lib

Usage

Configuration

Each backend requires specific configuration before the server is initialized.

AWS

Set the following environment variables before starting your application:

  • AWS_ACCESS_KEY_ID
  • AWS_SECRET_ACCESS_KEY
  • AWS_DEFAULT_REGION

Refer to the AWS SDK configuration documentation for more info.

Prometheus

The Prometheus backend starts an HTTP server that exposes metrics at /metrics.

  • Python: port is set via the port keyword argument (default 8080).
  • Go: port defaults to 8080 if not set via WithPort.

Note: Prometheus requires all label names for a metric to be declared upfront. The label schema is locked on the first call for each metric name. Any subsequent call with a different set of label keys will cause an error: a ValueError in Python, a panic in Go. Make sure to use the same label keys consistently across all calls to the same metric.

Note: Label keys passed at call-site must not overlap with fixed label keys. Passing a key that matches a fixed label key will cause a ValueError in Python and a panic in Go.

Security

The /metrics endpoint is served over plain HTTP with no authentication or TLS. This follows the standard Prometheus pull model, where the Prometheus server scrapes from within a trusted network. Do not expose the metrics port to untrusted networks. Restrict access at the network level (security groups, firewall rules, or a service mesh policy) so that only the Prometheus scraper can reach the port.

No-op

No configuration required. All calls are silently ignored.


Initialization

The library is designed to be transparent: initialization is the only place where the backend is chosen. All metric recording calls are identical regardless of the backend in use.

Python

import os
from spacearth.metrics import MetricServer

provider    = os.getenv("METRIC_PROVIDER", "aws")
namespace   = os.getenv("METRIC_NAMESPACE", "default")
environment = os.getenv("ENVIRONMENT", "development")

labels     = {"environment": environment}
extra_args = {}

# Prometheus requires a port
if provider == "prometheus":
    extra_args["port"] = int(os.getenv("PROMETHEUS_PORT", "8080"))

metric_server = MetricServer.create_server(provider, namespace, labels, **extra_args)
# AWS:        set AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_DEFAULT_REGION
# Prometheus: set PROMETHEUS_PORT (default: 8080)
# No-op:      no configuration required

Go

import (
    "os"

    metrics "github.com/Spacearth-NAV/metrics-lib/go"
)

func envOr(key, fallback string) string {
    if v := os.Getenv(key); v != "" {
        return v
    }
    return fallback
}

provider    := envOr("METRIC_PROVIDER", "aws")
namespace   := envOr("METRIC_NAMESPACE", "default")
environment := envOr("ENVIRONMENT", "development")

opts := []metrics.Option{
    metrics.WithFixedLabels(metrics.Label{Key: "environment", Value: environment}),
}

if provider == "prometheus" {
    port, _ := strconv.Atoi(envOr("PROMETHEUS_PORT", "8080"))
    opts = append(opts, metrics.WithPort(port))
}

metricsServer, err := metrics.NewServer(metrics.ServerType(provider), namespace, opts...)
if err != nil {
    // handle error
}
// AWS:        set AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_DEFAULT_REGION
// Prometheus: starts on :8080 by default; override with metrics.WithPort(port)
// No-op:      no configuration required

Recording metrics

All backends share the same interface. Fixed labels passed at initialization are automatically added to every metric.

Counters — add_observation / AddObservation

Records a single event count.

Python

metric_server.add_observation("requests_received", 1, labels={"endpoint": "/login"})

Go

metricsServer.AddObservation("requests_received", 1, metrics.Label{"endpoint", "/login"})

With the Prometheus backend, counters are exposed with the standard _total suffix (e.g. <namespace>_requests_received_total). Both languages append it automatically unless the name already ends with it.

Histograms — measure_time / MeasureTime

Records a duration. Python accepts seconds as a float; Go accepts a time.Duration.

Python

import time

t_start = time.time()
# ... do work ...
metric_server.measure_time("processing_time", time.time() - t_start, labels={"step": "auth"})

Go

start := time.Now()
// ... do work ...
metricsServer.MeasureTime("processing_time", time.Since(start), metrics.Label{"step", "auth"})

Gauges — increment_value / decrement_value / set_value

Tracks a value that goes up and down.

Python

def on_connection(conn):
    metric_server.increment_value("active_connections", labels={"endpoint": "/ws"})
    try:
        while conn.connected:
            pass
    finally:
        metric_server.decrement_value("active_connections", labels={"endpoint": "/ws"})

# or set an absolute value
metric_server.set_value("queue_depth", 42)

Go

metricsServer.IncrementValue("active_connections", 1, metrics.Label{"endpoint", "/ws"})
metricsServer.DecrementValue("active_connections", 1, metrics.Label{"endpoint", "/ws"})

metricsServer.SetValue("queue_depth", 42)

Known limitations

No graceful shutdown (Prometheus backend)

The Prometheus backend starts an HTTP server in a background goroutine. Neither the Server interface nor any concrete implementation exposes a Close or Shutdown method. The HTTP listener is held until the process exits.

If your application needs to stop the metrics server cleanly — for example, in integration tests that create multiple servers — this must be handled at the process level (e.g. via os.Signalos.Exit), not through this library.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

spacearth_metrics-1.1.1.tar.gz (13.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

spacearth_metrics-1.1.1-py3-none-any.whl (14.7 kB view details)

Uploaded Python 3

File details

Details for the file spacearth_metrics-1.1.1.tar.gz.

File metadata

  • Download URL: spacearth_metrics-1.1.1.tar.gz
  • Upload date:
  • Size: 13.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for spacearth_metrics-1.1.1.tar.gz
Algorithm Hash digest
SHA256 b311de372c6af5118f8ed86dab9addcfb18ada6ba4e5f1936379c0b8d18a9c66
MD5 1b1550b49ec73d7069c53fb09e7ecc85
BLAKE2b-256 1ada9dc159ee11b0bc497464234106742310691893d24ab1a7417ae9bc175221

See more details on using hashes here.

Provenance

The following attestation bundles were made for spacearth_metrics-1.1.1.tar.gz:

Publisher: publish.yml on Spacearth-NAV/metrics-lib

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file spacearth_metrics-1.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for spacearth_metrics-1.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 6078062555d8f4e3233c528a21c76bceaf397501abcac01408046ddc456aeaac
MD5 0b84bc6f8c6fc915f887ece8ecae3b55
BLAKE2b-256 29e925609916940aeea8d3ffe7e9c46c26dd1a1956b592018ecb63d726395028

See more details on using hashes here.

Provenance

The following attestation bundles were made for spacearth_metrics-1.1.1-py3-none-any.whl:

Publisher: publish.yml on Spacearth-NAV/metrics-lib

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

This release

1.1.1 This release

2 files

1.1.0

2 files

1.0.1

2 files

1.0.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page