-
Notifications
You must be signed in to change notification settings - Fork 13
feat: API-Server - Added OTel trace id auto-instrumentation for FastAPI #82
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
Merged
Changes from all commits
Commits
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| """ | ||
| OpenTelemetry tracing configuration for FastAPI applications. | ||
|
|
||
| This module sets up distributed tracing with OTLP exporter for sending traces | ||
| to an OpenTelemetry collector endpoint. | ||
| """ | ||
|
|
||
| import fastapi | ||
| import logging | ||
| import os | ||
|
|
||
| from opentelemetry import trace | ||
| from opentelemetry.exporter.otlp.proto.grpc import ( | ||
| trace_exporter as otel_grpc_trace_exporter, | ||
| ) | ||
| from opentelemetry.exporter.otlp.proto.http import ( | ||
| trace_exporter as otel_http_trace_exporter, | ||
| ) | ||
| from opentelemetry.instrumentation import fastapi as otel_fastapi | ||
| from opentelemetry.sdk import resources as otel_resources | ||
| from opentelemetry.sdk import trace as otel_trace | ||
| from opentelemetry.sdk.trace import export as otel_trace_export | ||
|
|
||
| _logger = logging.getLogger(__name__) | ||
|
|
||
| _OTEL_PROTOCOL_GRPC = "grpc" | ||
| _OTEL_PROTOCOL_HTTP = "http" | ||
| _OTEL_PROTOCOLS = (_OTEL_PROTOCOL_GRPC, _OTEL_PROTOCOL_HTTP) | ||
|
|
||
|
|
||
| def setup_api_tracing(app: fastapi.FastAPI) -> None: | ||
| """ | ||
| Configure OpenTelemetry tracing for a FastAPI application. | ||
|
|
||
| Args: | ||
| app: The FastAPI application instance to instrument | ||
|
|
||
| Environment Variables: | ||
| TANGLE_OTEL_EXPORTER_ENDPOINT: The endpoint URL for the OTLP collector | ||
| (e.g., "http://localhost:4317") | ||
| TANGLE_ENV: Environment name to include in service name | ||
| (defaults to "development") | ||
| TANGLE_OTEL_EXPORTER_PROTOCOL: The protocol to use for the OTLP exporter | ||
| (defaults to "grpc", can be "http") | ||
| """ | ||
| otel_endpoint = os.environ.get("TANGLE_OTEL_EXPORTER_ENDPOINT") | ||
| if not otel_endpoint: | ||
| return | ||
|
|
||
| app_env = os.environ.get("TANGLE_ENV", "development") | ||
| otel_protocol = os.environ.get("TANGLE_OTEL_EXPORTER_PROTOCOL", _OTEL_PROTOCOL_GRPC) | ||
| service_name = f"tangle-{app_env}" | ||
|
|
||
| try: | ||
| _logger.info( | ||
| f"Configuring OpenTelemetry tracing, endpoint={otel_endpoint}, protocol={otel_protocol}, service_name={service_name}" | ||
| ) | ||
|
|
||
| _validate_otel_config(otel_endpoint, otel_protocol) | ||
|
|
||
| if otel_protocol == _OTEL_PROTOCOL_GRPC: | ||
| otel_exporter = otel_grpc_trace_exporter.OTLPSpanExporter( | ||
| endpoint=otel_endpoint | ||
| ) | ||
| else: | ||
| otel_exporter = otel_http_trace_exporter.OTLPSpanExporter( | ||
| endpoint=otel_endpoint | ||
| ) | ||
|
|
||
| resource = otel_resources.Resource( | ||
| attributes={otel_resources.SERVICE_NAME: service_name} | ||
| ) | ||
| tracer_provider = otel_trace.TracerProvider(resource=resource) | ||
| span_processor = otel_trace_export.BatchSpanProcessor(otel_exporter) | ||
| tracer_provider.add_span_processor(span_processor) | ||
| trace.set_tracer_provider(tracer_provider) | ||
|
|
||
| # FastAPI auto-instrumentation docs: | ||
| # https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/fastapi/fastapi.html | ||
| otel_fastapi.FastAPIInstrumentor.instrument_app(app) | ||
|
|
||
| _logger.info(f"OpenTelemetry tracing configured successfully.") | ||
|
|
||
| except Exception as e: | ||
| _logger.exception(f"Failed to configure OpenTelemetry tracing: {e}") | ||
|
|
||
|
|
||
| def _validate_otel_config(otel_endpoint: str, otel_protocol: str) -> None: | ||
| """Validate OTel configuration. Raises ValueError if invalid.""" | ||
| if not otel_endpoint.startswith(("http://", "https://")): | ||
| raise ValueError( | ||
| f"Invalid OTel endpoint format: {otel_endpoint}. Expected format: http://<host>:<port> or https://<host>:<port>" | ||
| ) | ||
| if otel_protocol not in _OTEL_PROTOCOLS: | ||
| raise ValueError( | ||
| f"Invalid OTel protocol: {otel_protocol}. Expected values: {_OTEL_PROTOCOL_GRPC}, {_OTEL_PROTOCOL_HTTP}" | ||
| ) |
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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thank you for making it non-invasive.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
😀