Arun RS
05/12/2025, 6:32 AMArun RS
05/12/2025, 7:35 AMimport requests
import time
import json # Used only for pretty printing the payload
# --- Configuration ---
# Replace with your SigNoz Cloud region (e.g., 'us', 'in', 'eu')
REGION = "us"
# Replace with your actual SigNoz Ingestion Key
INGESTION_KEY = "<SIGNOZ KEY>"
# SigNoz Cloud OTLP metrics ingestion endpoint
ENDPOINT = f"<https://ingest>.{REGION}.signoz.cloud:443/v1/metrics"
# --- Generate OTLP Metrics Payload (JSON Format) ---
# Get current timestamp in nanoseconds (requires Python 3.7+)
# For older Python, use int(time.time() * 1e9)
current_time_nano = time.time_ns()
# OTLP Metrics JSON payload (simplified example for a single gauge metric)
# This structure must adhere to the OpenTelemetry Protocol specification
otlp_payload = {
"resourceMetrics": [
{
"resource": {
"attributes": [
{
"key": "service.name",
"value": {"stringValue": "my-python-script"}
},
{
"key": "host.name",
"value": {"stringValue": "my-python-machine"}
}
]
},
"scopeMetrics": [
{
"scope": {
"name": "my-manual-instrumentation",
"version": "1.0.0"
},
"metrics": [
{
"name": "my_custom_gauge_metric",
"description": "A custom metric sent via Python requests",
"unit": "1",
"gauge": {
"dataPoints": [
{
"attributes": [
{
"key": "status",
"value": {"stringValue": "operational"}
}
],
"startTimeUnixNano": str(current_time_nano), # Timestamps should be strings in OTLP JSON
"timeUnixNano": str(current_time_nano),
"asDouble": 99.9
}
]
}
}
]
}
]
}
]
}
# --- Prepare Headers ---
headers = {
# requests library will automatically set Content-Type: application/json when using the 'json' parameter
"signoz-ingestion-key": INGESTION_KEY
}
# --- Make the HTTPS POST Request ---
print(f"Sending metrics to: {ENDPOINT}")
print(f"Headers: {headers}")
# Use json.dumps for pretty printing, requests handles dict -> JSON serialization
print("Payload:")
print(json.dumps(otlp_payload, indent=2))
try:
# Using the 'json' parameter automatically serializes the dictionary to JSON
# and sets the 'Content-Type' header to 'application/json'
response = <http://requests.post|requests.post>(ENDPOINT, headers=headers, json=otlp_payload)
# --- Process Response ---
print(f"\nResponse Status Code: {response.status_code}")
print(f"Response Headers: {response.headers}")
print(f"Response Body: {response.text}")
if response.status_code >= 200 and response.status_code < 300:
print("\nMetrics sent successfully!")
else:
print("\nFailed to send metrics.")
except requests.exceptions.RequestException as e:
print(f"\nAn error occurred: {e}")