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.

Release files for spacearth-metrics 1.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for spacearth-metrics 1.1.1
File Size Uploaded
spacearth_metrics-1.1.1.tar.gz 13.3 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for spacearth-metrics 1.1.1
File Interpreter ABI Platform
spacearth_metrics-1.1.1-py3-none-any.whl Python 3 none any Details

Total release size:28.0 kB

Release files / spacearth_metrics-1.1.1.tar.gz

Download URL spacearth_metrics-1.1.1.tar.gz
Size 13.3 kB
Tags Source
SHA-256 checksum
How to use checksums
b311de372c6af5118f8ed86dab9addcfb18ada6ba4e5f1936379c0b8d18a9c66
BLAKE2b-256 checksum
How to use checksums
1ada9dc159ee11b0bc497464234106742310691893d24ab1a7417ae9bc175221
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.12

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jul 10, 2026.

Transparency log

Release files / spacearth_metrics-1.1.1-py3-none-any.whl

Download URL spacearth_metrics-1.1.1-py3-none-any.whl
Size 14.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6078062555d8f4e3233c528a21c76bceaf397501abcac01408046ddc456aeaac
BLAKE2b-256 checksum
How to use checksums
29e925609916940aeea8d3ffe7e9c46c26dd1a1956b592018ecb63d726395028
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.12

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jul 10, 2026.

Transparency log

Release history Release notifications | RSS feed

This release

1.1.1 This release

2 release files

1.1.0

2 release files

1.0.1

2 release files

1.0.0

2 release 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