diff --git a/forms-flow-api-utils/src/formsflow_api_utils/utils/__init__.py b/forms-flow-api-utils/src/formsflow_api_utils/utils/__init__.py index c580c797c..9b993da41 100644 --- a/forms-flow-api-utils/src/formsflow_api_utils/utils/__init__.py +++ b/forms-flow-api-utils/src/formsflow_api_utils/utils/__init__.py @@ -60,3 +60,4 @@ from .sentry import init_sentry from .formio import generate_formio_patch_request from .test_utils import get_token +from .telemetry import setup_tracing diff --git a/forms-flow-api-utils/src/formsflow_api_utils/utils/telemetry.py b/forms-flow-api-utils/src/formsflow_api_utils/utils/telemetry.py new file mode 100644 index 000000000..6b2619ca5 --- /dev/null +++ b/forms-flow-api-utils/src/formsflow_api_utils/utils/telemetry.py @@ -0,0 +1,36 @@ +"""This exposes Opentelemetry service.""" + +import os + +from opentelemetry import trace +from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import ( + OTLPSpanExporter, +) +from opentelemetry.instrumentation.flask import FlaskInstrumentor +from opentelemetry.instrumentation.requests import RequestsInstrumentor +from opentelemetry.sdk.resources import Resource +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import BatchSpanProcessor + + +def setup_tracing(app, service_name): + """Sets up OpenTelemetry tracing for the application.""" + # Check if OpenTelemetry tracing is enabled + if os.getenv("ENABLE_OPENTELEMETRY", "false").lower() != "true": + app.logger.info("OpenTelemetry tracing is disabled.") + return + + resource = Resource.create({"service.name": service_name}) + trace_provider = TracerProvider(resource=resource) + trace.set_tracer_provider(trace_provider) + + # Configure the OTLP exporter to send data to the OpenTelemetry Collector + otlp_endpoint = os.getenv("OTLP_ENDPOINT") + otlp_exporter = OTLPSpanExporter(endpoint=otlp_endpoint, insecure=True) + + # Add the OTLP exporter to the tracer provider + otlp_span_processor = BatchSpanProcessor(otlp_exporter) + trace_provider.add_span_processor(otlp_span_processor) + + FlaskInstrumentor().instrument_app(app) + RequestsInstrumentor().instrument()