FastAPI
The example below is using the Python guide for OpenTelemetry (opens in a new tab).
Libraries
First, install the required dependencies.
>_ Terminal
pip install opentelemetry-distro opentelemetry-exporter-otlp opentelemetry-instrumentation-fastapi
Instrumentation
Method: Code changes
There are many ways to instrument your FastAPI service. The below example requires updating your code.
main.py
import logging
from fastapi import FastAPI
from opentelemetry.sdk.resources import SERVICE_NAME, Resource
from opentelemetry.trace import set_tracer_provider
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry._logs import set_logger_provider
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
app = FastAPI()
logger = logging.getLogger("your-service-name")
resource = Resource(attributes={
SERVICE_NAME: "your-service-name"
})
trace_provider = TracerProvider(resource=resource)
processor = BatchSpanProcessor(OTLPSpanExporter())
trace_provider.add_span_processor(processor)
trace.set_tracer_provider(trace_provider)
log_provider = LoggerProvider(resource=resource)
log_processor = BatchLogRecordProcessor(OTLPLogExporter())
log_provider.add_log_record_processor(log_processor)
set_logger_provider(log_provider)
logger.addHandler(LoggingHandler(logger_provider=log_provider))
FastAPIInstrumentor.instrument_app(app)
Method: Agent
If you prefer not to update your code, you will need to bootstrap your service.
>_ Terminal
opentelemetry-bootstrap -a install
Run the agent
>_ Terminal
opentelemetry-instrument \
--service_name your-service-name \
python main.py # replace with your run command
Required configuration
The following environment variables are always required.
.env
OTEL_EXPORTER_OTLP_ENDPOINT="https://collect.smallhours.dev/"
OTEL_EXPORTER_OTLP_HEADERS="small-hours-api-key=YOUR_API_KEY,small-hours-service-id=YOUR_SERVICE_ID"