✨ Add native OpenTelemetry support (#16403)

This commit is contained in:
Sebastián Ramírez authored and GitHub committed 2026-09-29 19:25:55 +02:00
1 parent c30032a1b6
commit 4b3949cd9e
36 files changed
+5251 -46

No files matched your search

Whitespace-only changes.
@@ -0,0 +1,8 @@
import pytest
from tests.test_telemetry.conftest import remove_export_environment
@pytest.fixture(autouse=True)
def clean_environment(monkeypatch):
remove_export_environment(monkeypatch)
@@ -0,0 +1,8 @@
from fastapi.testclient import TestClient
def test_default_example():
from docs_src.opentelemetry.tutorial001_py310 import app
with TestClient(app) as client:
assert client.get("/items/1").json() == {"item_id": 1}
@@ -0,0 +1,28 @@
import json
from io import StringIO
from fastapi.testclient import TestClient
def test_console_provider_example(monkeypatch):
from opentelemetry.sdk.trace import export
output = StringIO()
exporter = export.ConsoleSpanExporter(
out=output, formatter=lambda span: span.to_json(indent=None) + "\n"
)
monkeypatch.setattr(export, "ConsoleSpanExporter", lambda: exporter)
from docs_src.opentelemetry.tutorial002_py310 import app, tracer_provider
try:
with TestClient(app) as client:
assert client.get("/items/2").json() == {"item_id": 2}
assert tracer_provider.force_flush()
spans = [json.loads(line) for line in output.getvalue().splitlines()]
assert len(spans) == 4
span = next(span for span in spans if span["kind"] == "SpanKind.SERVER")
assert span["name"] == "GET /items/{item_id}"
assert span["kind"] == "SpanKind.SERVER"
assert span["attributes"]["http.route"] == "/items/{item_id}"
finally:
tracer_provider.shutdown()
@@ -0,0 +1,22 @@
from fastapi.testclient import TestClient
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
def test_disable_operation_spans_example(monkeypatch):
exporter = InMemorySpanExporter()
provider = TracerProvider(shutdown_on_exit=False)
provider.add_span_processor(SimpleSpanProcessor(exporter))
monkeypatch.setattr(trace, "get_tracer_provider", lambda: provider)
from docs_src.opentelemetry.tutorial003_py310 import app
try:
with TestClient(app) as client:
assert client.get("/items/3").json() == {"item_id": 3}
(span,) = exporter.get_finished_spans()
assert span.kind == trace.SpanKind.SERVER
assert span.name == "GET /items/{item_id}"
finally:
provider.shutdown()