in use-cases/rag-pipeline/backend/src/backend_service.py [0:0]
def configure_cloud_trace(app):
"""Configures OpenTelemetry tracing with Cloud Trace exporter."""
try:
# Create a BatchSpanProcessor and add the exporter to it
span_processor = BatchSpanProcessor(OTLPSpanExporter())
# Detect environment. Set project ID if running on GCP
gcp_project_id = os.environ.get("GOOGLE_CLOUD_PROJECT")
resource = get_aggregated_resources(
[
Resource.create(
{
"service.name": "rag-service",
"service.version": "1.0",
"cloud.provider": "gcp",
"cloud.project.id": gcp_project_id,
}
)
]
)
# Create a TracerProvider and add the span processor
provider = TracerProvider(resource=resource)
provider.add_span_processor(span_processor)
# Set the TracerProvider as the global provider
trace.set_tracer_provider(provider)
# Instrument FastAPI app for automatic tracing
FastAPIInstrumentor.instrument_app(app, tracer_provider=provider)
# Get the tracer
tracer = trace.get_tracer(__name__)
# Configure custom logging to include trace_id and span_id
LoggingInstrumentor().instrument(set_logging_format=True)
logging.info("Cloud Trace configured successfully.")
return tracer # Return the tracer
except Exception as e:
logging.error(f"Error configuring Cloud Trace: {e}")
traceback.print_exc()
return None # Or handle the error appropriately