import os
import subprocess
import socket
from opentelemetry import trace, metrics
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.sdk.metrics.export import (
AggregationTemporality,
PeriodicExportingMetricReader,
)
from opentelemetry.exporter.otlp.proto.http.trace_exporter import (
OTLPSpanExporter
)
from opentelemetry.exporter.otlp.proto.http.metric_exporter import (
OTLPMetricExporter
)
def initialize_opentelemetry(service_name):
# Replace these values with your AppSignal application name, environment
# and push API key. These are used by the resource attributes configuration below.
name = "My app"
push_api_key = "0000-0000-0000-0000"
environment = "development"
# Replace `http://localhost:8099` with the address of your AppSignal collector
# if it's running on another host.
endpoint = "http://localhost:8099"
revision = subprocess.check_output(
"git rev-parse --short HEAD", shell=True, text=True
).strip()
resource = Resource(attributes={
"appsignal.config.name": name,
"appsignal.config.environment": environment,
"appsignal.config.push_api_key": push_api_key,
"appsignal.config.revision": revision,
"appsignal.config.language_integration": "python",
"appsignal.config.app_path": os.getcwd()
"host.name": socket.gethostname(),
# Customize the service name
"service.name": service_name,
})
trace_provider = TracerProvider(resource=resource)
span_processor = BatchSpanProcessor(
OTLPSpanExporter(endpoint=f"{collector_host}/v1/traces")
)
trace_provider.add_span_processor(span_processor)
trace.set_tracer_provider(trace_provider)
metric_exporter = OTLPMetricExporter(
endpoint=f"{collector_host}/v1/metrics",
)
metric_reader = PeriodicExportingMetricReader(
metric_exporter,
export_interval_millis=10000
)
metric_provider = MeterProvider(
resource=resource,
metric_readers=[metric_reader]
)
metrics.set_meter_provider(metric_provider)