Skip to main content

Unified metrics library supporting DataDog (DogStatsD) and OpenTelemetry/OpenObserve with automatic backend selection and dual-write mode.

Project description

grass-metrics

Unified metrics library for Grass projects. Supports DataDog (DogStatsD/UDP) and OpenTelemetry/OpenObserve (OTLP gRPC/HTTP) with automatic backend selection and dual-write mode.

Installation

# Core (no backend dependencies -- bring your own)
pip install grass-metrics

# With DataDog support
pip install "grass-metrics[datadog]"

# With OpenTelemetry support
pip install "grass-metrics[otel]"

# Both backends
pip install "grass-metrics[all]"

Quick Start

from grass_metrics import create_metrics_manager

metrics = create_metrics_manager()

metrics.increment("wl.my_service.items.processed")
metrics.gauge("wl.my_service.queue.size", 42)
metrics.histogram("wl.my_service.latency_seconds", 1.23)

# With extra tags
metrics.increment("wl.my_service.uploads.success", extra_tags=["provider:s3"])

# Shutdown (flushes OTel buffers)
metrics.shutdown()

Backend Selection

The factory picks the backend in this priority order:

Priority Source Example
1 backend argument to create_metrics_manager() create_metrics_manager("otel")
2 METRICS_BACKEND env var METRICS_BACKEND=dual
3 Local Redis key metrics_backend Set by preloader from cluster config
4 Default "datadog"

Supported values: datadog, otel, dual

  • datadog -- Sends metrics via DogStatsD UDP to the DataDog Agent
  • otel -- Sends metrics via OTLP (gRPC or HTTP) to an OpenTelemetry Collector / OpenObserve
  • dual -- Sends to both simultaneously (DataDog primary, OTel secondary). Useful during migration.

Environment Variables

Common

Variable Description Default
METRICS_BACKEND Backend selection datadog
ENVIRONMENT Environment name for tags unknown
CLUSTER_NAME or CLUSTERNAME Cluster name for tags unknown
HOSTNAME Host name for tags unknown
SERVICE_NAME Service name for tags -
POD_NAME Pod name for tags (optional) -
LOCAL_REDIS_DB_URI Redis URI for dynamic backend override -

DataDog

Variable Description Default
DD_AGENT_HOST DataDog agent host 172.17.0.1
DD_DOGSTATSD_PORT DogStatsD port 8125

OpenTelemetry / OpenObserve

Variable Description Default
OTEL_EXPORTER_ENDPOINT OTLP endpoint auto (see below)
OTEL_EXPORTER_AUTH_TOKEN Auth header value -
NODE_IP K8s node IP for local agent -

OTel endpoint resolution: explicit > OTEL_EXPORTER_ENDPOINT > http://{NODE_IP}:4317 > gateway fallback.

Kubernetes Pod Spec

env:
  - name: METRICS_BACKEND
    valueFrom:
      configMapKeyRef:
        name: scraper-config
        key: metrics_backend
  # DataDog
  - name: DD_AGENT_HOST
    valueFrom:
      fieldRef:
        fieldPath: status.hostIP
  # OTel
  - name: NODE_IP
    valueFrom:
      fieldRef:
        fieldPath: status.hostIP

Docker Compose

environment:
  METRICS_BACKEND: "otel"
  DD_AGENT_HOST: "datadog"          # service name
  OTEL_EXPORTER_ENDPOINT: "http://otel-collector:4317"

Domain-Specific Metrics (Consumer Pattern)

For projects with many metrics, wrap MetricsManager in a thin domain class:

from grass_metrics import create_metrics_manager

class YtdMetrics:
    DOWNLOADS_SUCCESS = "wl.ytd.downloads.healthy_count"
    DOWNLOADS_FAILED  = "wl.ytd.downloads.failed_count"
    UPLOAD_DURATION   = "wl.ytd.upload.duration_seconds"

    def __init__(self):
        self._m = create_metrics_manager()

    def increment_downloaded_videos_count(self):
        self._m.increment(self.DOWNLOADS_SUCCESS)

    def increment_failed_downloads_count(self):
        self._m.increment(self.DOWNLOADS_FAILED)

    def send_upload_duration(self, seconds: float):
        self._m.histogram(self.UPLOAD_DURATION, seconds)

    def shutdown(self):
        self._m.shutdown()

Direct Publisher Access

For advanced use cases, publishers can be used directly:

from grass_metrics import DatadogPublisher, OtelPublisher

dd = DatadogPublisher(statsd_host="172.17.0.1", statsd_port=8125)
dd.increment_count("my.counter", 1, ["env:prod"])

otel = OtelPublisher(service_name="my-svc", use_grpc=True)
otel.increment_count("my.counter", 1, ["env:prod"])
otel.shutdown()

Architecture

┌──────────────────────────────────────────────────┐
│                Consumer Project                   │
│  (e.g. YtdMetrics with domain-specific methods)  │
└──────────────────────┬───────────────────────────┘
                       │
         create_metrics_manager(backend=...)
                       │
                ┌──────▼──────┐
                │   Factory    │  resolves backend from
                │  factory.py  │  env / Redis / default
                └──────┬──────┘
                       │
          ┌────────────┼────────────┐
          │            │            │
    ┌─────▼─────┐ ┌───▼────┐ ┌────▼─────┐
    │ MetricsMgr│ │MetrMgr │ │ DualMgr  │
    │ + DD Pub  │ │+ OTel  │ │ DD + OTel│
    └───────────┘ └────────┘ └──────────┘

Project details


Download files

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

Source Distribution

grass_metrics-0.1.0.tar.gz (12.4 kB view details)

Uploaded Source

Built Distribution

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

grass_metrics-0.1.0-py3-none-any.whl (13.3 kB view details)

Uploaded Python 3

File details

Details for the file grass_metrics-0.1.0.tar.gz.

File metadata

  • Download URL: grass_metrics-0.1.0.tar.gz
  • Upload date:
  • Size: 12.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for grass_metrics-0.1.0.tar.gz
Algorithm Hash digest
SHA256 8bdba4626fd8a0ef117b2756ff76dfb292a50b593cfd7aafad6b48d3c96e2941
MD5 9d7ff80d0c92a9744ea225805ea4a4ff
BLAKE2b-256 7d40535e621e68d37e3bd6416c663cfd638255e0226bee6bb9ee154a32737a75

See more details on using hashes here.

File details

Details for the file grass_metrics-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: grass_metrics-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 13.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for grass_metrics-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 225f818145e6abf6eb2ac1a50d4083db6e955d1b826bf66b10bf2278b1415e72
MD5 54f3a0a0ec972427d2bcb54fb74f0b14
BLAKE2b-256 5a9d32b6fa03023a3baa660943f96c43a3c91f5ea88a96ced19bb7533a33ed3e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page