Skip to main content

Pushing metrics to metrics platform

In this guide, we'll be going through the steps of securely pushing metrics to our metrics platform from code

Set up open telemetry credentials

In order to push metrics we need to be authenticated. We rely on OAuth in order to authenticate. Here is how you get an OAuth service account for pushing metrics to the metrics platform.

Here is an example

Find the oauth settings

In the example PR we created a service account - Azure Active Directory (AAD) Application named gl-example-opentelemetry-client-test. Together with this AAD application, Terraform workflow created a password with an expiration period of 1 year. The application name (gl-example-opentelemetry-client-test-client-id) and password gl-example-opentelemetry-client-test-client-secret are stored in the specified key-vault. The below application code example uses gl-example-opentelemetry-client-test-client-id as client_id and gl-example-opentelemetry-client-test-client-secret as client_secret.

Python code

requirements.txt

opentelemetry-api
opentelemetry-sdk
opentelemetry-exporter-otlp
import os
import requests
from opentelemetry import metrics
from opentelemetry.sdk.resources import SERVICE_NAME, Resource

from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader

token_url = "https://login.microsoftonline.com/9c644eac-5362-44db-8e9c-b2be20cee933/oauth2/v2.0/token"
client_id = os.getenv("OTEL_CLIENT_ID", "dummy_id")
client_secret = os.getenv("OTEL_CLIENT_SECRET", "dummy_secret")
scope = "api://gjensidige-opentelemetry-auth-server-test/.default"

response = requests.post(
token_url,
data={
"grant_type": "client_credentials",
"scope": scope,
"client_id": client_id,
"client_secret": client_secret
}
)
response.raise_for_status()
access_token = response.json()["access_token"]
exporter = OTLPMetricExporter(
endpoint="https://otel-collector-otlp2.tools-mgt.testgjensidige.io/v1/metrics",
headers={"Authorization": f"Bearer {access_token}"},
timeout=30,
)
resource = Resource.create(attributes={
SERVICE_NAME: "otel-example-service"
})

reader = PeriodicExportingMetricReader(exporter)
provider = MeterProvider(resource=resource, metric_readers=[reader])
metrics.set_meter_provider(provider)

meter = metrics.get_meter("otel-example-meter")
counter = meter.create_counter("otel_example_counter")
counter.add(1, {"env": "dev"})

Running the python example

export OTEL_CLIENT_ID="THE CLIENT ID YOU HAVE"
export OTEL_CLIENT_SECRET="THE CLIENT SECRET YOU HAVE"
pip install -r requirements.txt
python otel-exporter.py