span_id и trace_id
Deploy / deploy (push) Successful in 51s

This commit is contained in:
Раис Юсупалиев
2026-06-20 19:46:48 +03:00
parent 798b6e38bd
commit 6a3da82ddc
5 changed files with 108 additions and 2 deletions
+47
View File
@@ -3,6 +3,8 @@ import logging
from io import StringIO
import structlog
from opentelemetry import trace
from opentelemetry.trace import NonRecordingSpan, SpanContext, TraceFlags
from app.runtime.logging import configure_logging
@@ -20,6 +22,8 @@ def test_application_log_is_serialized_as_json() -> None:
assert payload["level"] == "info"
assert payload["logger"] == "app.test"
assert isinstance(payload["timestamp"], str)
assert "trace_id" not in payload
assert "span_id" not in payload
_reset_logging()
@@ -75,6 +79,49 @@ def test_uvicorn_loggers_use_shared_json_logging_setup() -> None:
_reset_logging()
def test_active_trace_context_is_added_to_structlog_and_standard_logs() -> None:
stream = StringIO()
trace_id = 0x1234567890ABCDEF1234567890ABCDEF
span_id = 0x1234567890ABCDEF
span = NonRecordingSpan(
SpanContext(
trace_id=trace_id,
span_id=span_id,
is_remote=False,
trace_flags=TraceFlags.SAMPLED,
)
)
configure_logging(stream=stream)
with trace.use_span(span, end_on_exit=False):
structlog.get_logger("app.test").info("structured_event")
logging.getLogger("app.test").info("standard_event")
records = [json.loads(line) for line in stream.getvalue().splitlines()]
expected_trace_id = "1234567890abcdef1234567890abcdef"
expected_span_id = "1234567890abcdef"
assert [record["trace_id"] for record in records] == [
expected_trace_id,
expected_trace_id,
]
assert [record["span_id"] for record in records] == [
expected_span_id,
expected_span_id,
]
assert records[0]["event"] == (
f'structured_event span_id="{expected_span_id}" '
f'trace_id="{expected_trace_id}"'
)
assert records[1]["event"] == (
f'standard_event span_id="{expected_span_id}" '
f'trace_id="{expected_trace_id}"'
)
_reset_logging()
def _reset_logging() -> None:
structlog.reset_defaults()
root_logger = logging.getLogger()