-
Notifications
You must be signed in to change notification settings - Fork 2
feat: Integrate OpenTelemetry #189
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
4628a95
wip
khvn26 039e8a2
cleaner api, excluded paths
khvn26 dad413c
same span names as log_extra, openapi
khvn26 a4aa83f
improve instrumentation scope
khvn26 f11be93
add docs
khvn26 d3f811e
add trace_id and span_id to structured logs
khvn26 850b26e
fix test
khvn26 0ffbeaf
nicer fixture
khvn26 80faba4
even nicer fixture
khvn26 241a6d5
add missing tests
khvn26 065d535
add psycopg2, redis instrumenters
khvn26 0bc8d45
add span events as well
khvn26 f61e6a9
add flagsmith.event
khvn26 56b0b3e
use normalised routes for http.route attribute values
khvn26 9f3f6a1
restore severity text
khvn26 0a3f1cf
fix tests
khvn26 eabc583
fix docs
khvn26 bbe9107
simplify baggage test: remove unnecessary try/finally
khvn26 7657026
remove redundant tests
khvn26 bad5a92
account for empty log bodies
khvn26 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,204 @@ | ||
| import contextlib | ||
| import json | ||
| from collections.abc import Generator | ||
| from datetime import datetime, timezone | ||
| from importlib.metadata import version | ||
| from typing import cast | ||
|
|
||
| import inflection | ||
| import structlog | ||
| from opentelemetry import baggage, trace | ||
| from opentelemetry import context as otel_context | ||
| from opentelemetry._logs import SeverityNumber | ||
| from opentelemetry.baggage.propagation import W3CBaggagePropagator | ||
| from opentelemetry.exporter.otlp.proto.http._log_exporter import ( | ||
| OTLPLogExporter, | ||
| ) | ||
| from opentelemetry.exporter.otlp.proto.http.trace_exporter import ( | ||
| OTLPSpanExporter, | ||
| ) | ||
| from opentelemetry.instrumentation.django import DjangoInstrumentor | ||
| from opentelemetry.instrumentation.psycopg2 import Psycopg2Instrumentor | ||
| from opentelemetry.instrumentation.redis import RedisInstrumentor | ||
| from opentelemetry.propagate import set_global_textmap | ||
| from opentelemetry.propagators.composite import CompositePropagator | ||
| from opentelemetry.propagators.textmap import TextMapPropagator | ||
| from opentelemetry.sdk._logs import LoggerProvider | ||
| from opentelemetry.sdk._logs.export import BatchLogRecordProcessor | ||
| from opentelemetry.sdk.resources import Resource | ||
| from opentelemetry.sdk.trace import TracerProvider | ||
| from opentelemetry.sdk.trace.export import BatchSpanProcessor | ||
| from opentelemetry.trace.propagation.tracecontext import ( | ||
| TraceContextTextMapPropagator, | ||
| ) | ||
| from opentelemetry.util.types import AnyValue, Attributes | ||
| from structlog.typing import EventDict, Processor | ||
|
|
||
| _SEVERITY_MAP: dict[str, SeverityNumber] = { | ||
| "debug": SeverityNumber.DEBUG, | ||
| "info": SeverityNumber.INFO, | ||
| "warning": SeverityNumber.WARN, | ||
| "error": SeverityNumber.ERROR, | ||
| "critical": SeverityNumber.FATAL, | ||
| } | ||
|
|
||
| _RESERVED_KEYS = frozenset( | ||
| [ | ||
| "event", | ||
| "level", | ||
| "timestamp", | ||
| "logger", | ||
| "trace_id", | ||
| "span_id", | ||
| ] | ||
| ) | ||
|
|
||
|
|
||
| def add_otel_trace_context( | ||
| logger: structlog.types.WrappedLogger, | ||
| method_name: str, | ||
| event_dict: EventDict, | ||
| ) -> EventDict: | ||
| """Add ``trace_id`` and ``span_id`` from the active OTel span to the event dict.""" | ||
| span = trace.get_current_span() | ||
| ctx = span.get_span_context() | ||
| if ctx and ctx.is_valid: | ||
| event_dict["trace_id"] = f"{ctx.trace_id:032x}" | ||
| event_dict["span_id"] = f"{ctx.span_id:016x}" | ||
| return event_dict | ||
|
|
||
|
|
||
| def make_structlog_otel_processor(logger_provider: LoggerProvider) -> Processor: | ||
| """Create a structlog processor that emits log records to OpenTelemetry. | ||
|
|
||
| Sits in the processor chain *before* the final renderer so that | ||
| only structlog-originated logs reach OTel. Passes the event_dict | ||
| through unchanged so downstream processors (console/JSON renderers) | ||
| still work normally. | ||
|
|
||
| Pass the returned processor to :func:`~common.core.logging.setup_logging` | ||
| via ``otel_processor``. | ||
| """ | ||
| otel_logger = logger_provider.get_logger(__name__, version("flagsmith-common")) | ||
|
|
||
| def processor( | ||
| logger: structlog.types.WrappedLogger, | ||
| method_name: str, | ||
| event_dict: EventDict, | ||
| ) -> EventDict: | ||
| attributes = map_event_dict_to_otel_attributes(event_dict) | ||
|
|
||
| # Copy W3C baggage entries into log attributes so downstream | ||
| # exporters can access them. | ||
| ctx = otel_context.get_current() | ||
| for key, value in baggage.get_all(ctx).items(): | ||
| attributes[key] = str(value) | ||
emyller marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| body = event_dict.get("event", "") | ||
| logger_name = event_dict.get("logger") | ||
| event_name = inflection.underscore(body) if body else "unknown" | ||
| if logger_name: | ||
| event_name = f"{logger_name}.{event_name}" | ||
emyller marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| # Some observability platforms don't surface OTel's EventName. | ||
| # Keep a custom attribute for better visibility. | ||
| attributes["flagsmith.event"] = event_name | ||
|
|
||
| log_level = event_dict.get("level", method_name) | ||
|
|
||
| otel_logger.emit( | ||
| timestamp=int(datetime.now(timezone.utc).timestamp() * 1e9), | ||
| context=otel_context.get_current(), | ||
| severity_text=log_level, | ||
| severity_number=_SEVERITY_MAP.get(log_level, SeverityNumber.TRACE), | ||
emyller marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| body=body, | ||
| event_name=event_name, | ||
| attributes=attributes, | ||
| ) | ||
|
|
||
| # Also attach as a span event if there's an active span. | ||
| span = trace.get_current_span() | ||
| if span.is_recording(): | ||
| # AnyValue is a superset of AttributeValue at runtime; | ||
| # the cast keeps mypy happy. | ||
| span.add_event(event_name, attributes=cast(Attributes, attributes)) | ||
|
|
||
| return event_dict | ||
|
|
||
| return processor | ||
|
|
||
|
|
||
| def map_event_dict_to_otel_attributes(event_dict: EventDict) -> dict[str, AnyValue]: | ||
| return { | ||
| k.replace("__", "."): map_value_to_otel_value(v) | ||
| for k, v in event_dict.items() | ||
| if k not in _RESERVED_KEYS | ||
| } | ||
|
|
||
|
|
||
| def map_value_to_otel_value(value: object) -> str | int | float | bool: | ||
| """Coerce a value to an OTel-attribute-compatible type.""" | ||
| if isinstance(value, (bool, str, int, float)): | ||
| return value | ||
| return json.dumps(value, default=str) | ||
|
|
||
|
|
||
| def build_otel_log_provider(*, endpoint: str, service_name: str) -> LoggerProvider: | ||
| """Create and configure an OTel LoggerProvider with OTLP/HTTP export.""" | ||
| resource = Resource.create({"service.name": service_name}) | ||
| provider = LoggerProvider(resource=resource) | ||
| exporter = OTLPLogExporter(endpoint=endpoint) | ||
| provider.add_log_record_processor(BatchLogRecordProcessor(exporter)) | ||
| return provider | ||
|
|
||
|
|
||
| def build_tracer_provider(*, endpoint: str, service_name: str) -> TracerProvider: | ||
| """Create a TracerProvider with OTLP/HTTP export.""" | ||
| resource = Resource.create({"service.name": service_name}) | ||
| tracer_provider = TracerProvider(resource=resource) | ||
| span_exporter = OTLPSpanExporter(endpoint=endpoint) | ||
| tracer_provider.add_span_processor(BatchSpanProcessor(span_exporter)) | ||
| return tracer_provider | ||
|
|
||
|
|
||
| @contextlib.contextmanager | ||
| def setup_tracing( | ||
| tracer_provider: TracerProvider, | ||
| excluded_urls: str | None = None, | ||
| ) -> Generator[None, None, None]: | ||
| """Set up and tear down OTel distributed tracing with Django instrumentation. | ||
|
|
||
| Sets the global TracerProvider, configures W3C trace context + | ||
| baggage propagation, and instruments Django so that every request | ||
| creates a span with the incoming trace context. | ||
|
|
||
| On exit, uninstruments Django and shuts down the tracer provider. | ||
|
|
||
| Must be called *before* Django's WSGI app is created. | ||
|
|
||
| Args: | ||
| tracer_provider: The TracerProvider to use. | ||
| excluded_urls: Comma-separated URL paths to exclude from tracing | ||
| (e.g. ``"health/liveness,health/readiness"``). If not provided, | ||
| falls back to the ``OTEL_PYTHON_DJANGO_EXCLUDED_URLS`` env var. | ||
| """ | ||
| trace.set_tracer_provider(tracer_provider) | ||
|
|
||
| propagator: TextMapPropagator = CompositePropagator( | ||
| [ | ||
| TraceContextTextMapPropagator(), | ||
| W3CBaggagePropagator(), | ||
| ] | ||
| ) | ||
| set_global_textmap(propagator) | ||
|
|
||
| DjangoInstrumentor().instrument(excluded_urls=excluded_urls) | ||
| Psycopg2Instrumentor().instrument(enable_commenter=True, skip_dep_check=True) | ||
| RedisInstrumentor().instrument() | ||
| try: | ||
| yield | ||
| finally: | ||
| RedisInstrumentor().uninstrument() | ||
| Psycopg2Instrumentor().uninstrument() | ||
| DjangoInstrumentor().uninstrument() | ||
| tracer_provider.shutdown() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.