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.Signal → os.Exit), not through this library.

Metadata

Release files for spacearth-metrics 1.1.2

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.2
File Size Uploaded Provenance Actions
spacearth_metrics-1.1.2.tar.gz 13.4 kB With provenance Details for spacearth_metrics-1.1.2.tar.gz

Built distribution (wheel)

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

Total release size: 28.3 kB

Release files / spacearth_metrics-1.1.2.tar.gz

Download URL spacearth_metrics-1.1.2.tar.gz
Size 13.4 kB
Tags Source
SHA-256 checksum
How to use checksums
7bb0548cc96b3682bb33f9ba1c53ca40d7ce0cdff4d8b56a372e6f7fdc1fad31
BLAKE2b-256 checksum
How to use checksums
ec5710ecd104280cfacf9c97695e11ddbeedca4500264797f7021ec0f6c5f481
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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 Oct 13, 2026.

Transparency log

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

Download URL spacearth_metrics-1.1.2-py3-none-any.whl
Size 14.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
02c784c506646fdafb31c848ebb36b5fd262b6f75ffc09f090b6682a2f5f01d7
BLAKE2b-256 checksum
How to use checksums
34af80d52bf640c5c1698ea2a6605d01769b4f046d79d15d97a0c575b4ca3956
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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 Oct 13, 2026.

Transparency log

Security for spacearth-metrics 1.1.2

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.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for spacearth_metrics-1.1.2.tar.gz

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 Oct 13, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

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