OTEL Trace Ingestion
Publish OTEL Traces directly to your DBNL Deployment
Prerequisites
pip install opentelemetry-sdk>=1.20.0
pip install opentelemetry-exporter-otlp>=1.20.0pip install openinference-instrumentation-langchain>=0.1.0import os
import logging
from typing import Optional
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import Resource
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def create_dbnl_exporter() -> Optional[OTLPSpanExporter]:
"""Create OTLP exporter for DBNL"""
# Get configuration from environment
api_url = os.environ.get("DBNL_API_URL", "").strip()
api_token = os.environ.get("DBNL_API_TOKEN", "").strip()
project_id = os.environ.get("DBNL_PROJECT_ID", "").strip()
# Validate configuration
if not all([api_url, api_token, project_id]):
logger.info("DBNL configuration incomplete. Set DBNL_API_URL, DBNL_API_TOKEN, and DBNL_PROJECT_ID.")
return None
try:
# Create headers
headers = {
"Authorization": f"Bearer {api_token}",
"x-dbnl-project-id": project_id,
"Content-Type": "application/x-protobuf",
}
# Create exporter with hardcoded endpoint format
endpoint = f"https://{api_url}/otel/v1/traces"
exporter = OTLPSpanExporter(
endpoint=endpoint,
headers=headers
)
logger.info(f"✅ DBNL exporter configured: {endpoint}")
return exporter
except Exception as e:
logger.error(f"❌ Failed to configure DBNL exporter: {e}")
return None
def initialize_telemetry():
"""Initialize OpenTelemetry with DBNL exporter"""
# Create tracer provider with resource attributes
resource = Resource.create({
"service.name": os.environ.get("OTEL_SERVICE_NAME", "my-agent"),
})
tracer_provider = TracerProvider(resource=resource)
trace.set_tracer_provider(tracer_provider)
# Add DBNL exporter
dbnl_exporter = create_dbnl_exporter()
if dbnl_exporter:
processor = BatchSpanProcessor(dbnl_exporter)
tracer_provider.add_span_processor(processor)
logger.info("📊 DBNL OTEL tracing enabled")
else:
logger.info("ℹ️ DBNL OTEL tracing not configured")
return tracer_provider
# Initialize on import
tracer_provider = initialize_telemetry()
tracer = trace.get_tracer(__name__)from openinference.instrumentation.langchain import LangChainInstrumentor
def initialize_telemetry():
"""Initialize OpenTelemetry with DBNL exporter and LangChain instrumentation"""
# ... (previous code) ...
# Add LangChain instrumentation
try:
instrumentor = LangChainInstrumentor()
instrumentor.instrument(tracer_provider=tracer_provider)
logger.info("🔧 LangChain OpenInference instrumentation enabled")
except Exception as e:
logger.error(f"❌ Failed to instrument LangChain: {e}")
return tracer_providerfrom fastapi import FastAPI
from telemetry import initialize_telemetry
app = FastAPI()
@app.on_event("startup")
async def startup_event():
initialize_telemetry()
print("✅ Telemetry initialized")from telemetry import initialize_telemetry
if __name__ == "__main__":
initialize_telemetry()
# Your application code herefrom opentelemetry import trace
tracer = trace.get_tracer(__name__)
with tracer.start_as_current_span("agent_execution") as span:
# Set semantic attributes
span.set_attribute("input.value", user_query)
span.set_attribute("output.value", agent_response)
# Add custom metadata
span.set_attribute("session.id", session_id)
span.set_attribute("conversation.id", conversation_id)
span.set_attribute("tool.name", "search_symbol")
span.set_attribute("tool.success", True)
span.set_attribute("deployment.type", "web-application")from opentelemetry.sdk.trace.export import BatchSpanProcessor
processor = BatchSpanProcessor(dbnl_exporter)
tracer_provider.add_span_processor(processor)from opentelemetry.sdk.trace.export import SimpleSpanProcessor
processor = SimpleSpanProcessor(dbnl_exporter)
tracer_provider.add_span_processor(processor)from opentelemetry import trace
from telemetry import tracer_provider
tracer = trace.get_tracer(__name__)
# Create a test span
with tracer.start_as_current_span("test_dbnl_export") as span:
span.set_attribute("input.value", "test input")
span.set_attribute("output.value", "test output")
span.set_attribute("test", True)
# Force flush to ensure export
tracer_provider.force_flush()
print("✅ Test span exported to DBNL")echo $DBNL_API_URL
echo $DBNL_API_TOKEN
echo $DBNL_PROJECT_IDcurl -H "Authorization: Bearer $DBNL_API_TOKEN" \
-H "x-dbnl-project-id: $DBNL_PROJECT_ID" \
https://$DBNL_API_URL/health✅ DBNL exporter configured: https://api.dev.dbnl.com/otel/v1/traces
📊 DBNL OTEL tracing enabled# telemetry.py
import os
import logging
from typing import Optional
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import Resource
from openinference.instrumentation.langchain import LangChainInstrumentor
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def create_dbnl_exporter() -> Optional[OTLPSpanExporter]:
"""Create OTLP exporter for DBNL"""
api_url = os.environ.get("DBNL_API_URL", "").strip()
api_token = os.environ.get("DBNL_API_TOKEN", "").strip()
project_id = os.environ.get("DBNL_PROJECT_ID", "").strip()
if not all([api_url, api_token, project_id]):
logger.info("DBNL configuration incomplete")
return None
try:
headers = {
"Authorization": f"Bearer {api_token}",
"x-dbnl-project-id": project_id,
"Content-Type": "application/x-protobuf",
}
endpoint = f"https://{api_url}/otel/v1/traces"
exporter = OTLPSpanExporter(endpoint=endpoint, headers=headers)
logger.info(f"✅ DBNL exporter configured: {endpoint}")
return exporter
except Exception as e:
logger.error(f"❌ Failed to configure DBNL exporter: {e}")
return None
def initialize_telemetry():
"""Initialize OpenTelemetry with DBNL exporter"""
resource = Resource.create({
"service.name": os.environ.get("OTEL_SERVICE_NAME", "my-agent"), # Optional: identifies your service
})
tracer_provider = TracerProvider(resource=resource)
trace.set_tracer_provider(tracer_provider)
# Add DBNL exporter
dbnl_exporter = create_dbnl_exporter()
if dbnl_exporter:
processor = BatchSpanProcessor(dbnl_exporter)
tracer_provider.add_span_processor(processor)
logger.info("📊 DBNL OTEL tracing enabled")
# Add LangChain instrumentation
try:
instrumentor = LangChainInstrumentor()
instrumentor.instrument(tracer_provider=tracer_provider)
logger.info("🔧 LangChain instrumentation enabled")
except Exception as e:
logger.error(f"❌ Failed to instrument LangChain: {e}")
return tracer_provider
# Initialize
tracer_provider = initialize_telemetry()
tracer = trace.get_tracer(__name__)