-
Notifications
You must be signed in to change notification settings - Fork 231
feat: add X-Logfire-Telemetry header #1905
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
Open
adriangb
wants to merge
6
commits into
main
Choose a base branch
from
add-telemetry-header
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 5 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
51f03ce
feat: add X-Logfire-Telemetry header and surface server warnings/errors
adriangb ce5faf6
trim telemetry pairs, add service.instance.id, document rationale per…
adriangb 69df1d2
move service_instance_id into _config_telemetry_pairs
adriangb e9f80ab
Revert "Add user agent to query client (#1875)"
adriangb cab00d0
address review: JSON header value, implementation field, cache base p…
adriangb 78808fa
split out response-header handling into its own PR
adriangb 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,129 @@ | ||
| """SDK <-> server out-of-band metadata exchanged via custom HTTP headers. | ||
|
|
||
| * `X-Logfire-Telemetry` (request): non-sensitive information about the SDK and how | ||
| it is configured, encoded as a compact JSON object. Used by the backend to | ||
| answer questions like which SDK versions are still in active use, which Python | ||
| versions we can drop, and which configuration options users actually enable. | ||
| Secrets (`token`, `api_key`, `service_name`, etc.) are never included. | ||
| * `X-Logfire-Warning` (response): an out-of-band warning the server wants the | ||
| user to see. Surfaced via `warnings.warn(...)`; the standard "default" filter | ||
| deduplicates identical messages so a chatty server only warns once. | ||
| * `X-Logfire-Error` (response): an out-of-band error the server wants the SDK | ||
| to raise. Always raised — callers that want to keep working past it (the OTLP | ||
| pipeline, the variables provider) already swallow exceptions from their HTTP | ||
| calls. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import functools | ||
| import json | ||
| import sys | ||
| import warnings | ||
| from typing import TYPE_CHECKING, Any | ||
|
|
||
| import requests | ||
|
|
||
| from logfire.exceptions import LogfireServerError, LogfireServerWarning | ||
| from logfire.version import VERSION | ||
|
|
||
| if TYPE_CHECKING: | ||
| from .config import LogfireConfig | ||
|
|
||
|
|
||
| TELEMETRY_HEADER_NAME = 'X-Logfire-Telemetry' | ||
| WARNING_HEADER_NAME = 'X-Logfire-Warning' | ||
| ERROR_HEADER_NAME = 'X-Logfire-Error' | ||
|
|
||
|
|
||
| @functools.cache | ||
| def _base_telemetry_pairs() -> dict[str, Any]: | ||
| # Each field below has an explicit rationale; do not add a field unless you have one. | ||
| return { | ||
| # SDK version: the primary signal for deprecation planning — which versions | ||
| # are still in active use so we know when it is safe to drop one. | ||
| 'sdk_version': VERSION, | ||
| # SDK language: lets the same backend ingestion logic distinguish python | ||
| # from future SDKs (JS, Rust) without having to parse User-Agent. | ||
| 'sdk_language': 'python', | ||
| # Python version: tells us when we can drop support for an older Python. | ||
| 'python_version': f'{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}', | ||
| # Implementation: spotting non-CPython users (pypy, graalpy) before | ||
| # changing anything that depends on CPython-specific behaviour. | ||
| 'implementation': sys.implementation.name, | ||
| # OS: same idea — confirm Windows / Linux / macOS coverage before | ||
| # touching platform-sensitive code paths. | ||
| 'os': sys.platform, | ||
| } | ||
|
|
||
|
|
||
| def _config_telemetry_pairs(config: LogfireConfig) -> dict[str, Any]: | ||
| """Pick fields of `LogfireConfig` that are useful for product analytics. | ||
|
|
||
| Each field below has an explicit rationale; do not add a field unless you have | ||
| one. Everything else either duplicates information the server already knows, | ||
| isn't actionable, or risks leaking sensitive data (token, api_key, | ||
| service_name, environment, etc.). | ||
| """ | ||
| # Multi-project usage: how many users configure more than one write token in | ||
| # a single SDK instance. Drives auth/routing roadmap decisions. | ||
| token = config.token | ||
| if isinstance(token, list): | ||
| token_count = len(token) | ||
| elif token: | ||
| token_count = 1 | ||
| else: | ||
| token_count = 0 | ||
|
|
||
| pairs: dict[str, Any] = { | ||
| # Adoption signal for the `code_source=` option (newer feature): tells us | ||
| # whether the integration with the source-code link UI is worth investing in. | ||
| 'code_source_set': config.code_source is not None, | ||
| # Adoption signal for the variables / feature-flag feature (newer feature): | ||
| # informs whether to keep building on it. | ||
| 'variables_set': config.variables is not None, | ||
| 'token_count': token_count, | ||
| } | ||
|
|
||
| if config._service_instance_id: # pyright: ignore[reportPrivateUsage] | ||
| # Mirrors the OTLP resource attribute of the same name | ||
| # (https://opentelemetry.io/docs/specs/semconv/registry/attributes/service/#service-instance-id). | ||
| # Carrying it on the header lets the backend correlate metadata with the spans | ||
| # this SDK instance is exporting, even on requests that don't carry an OTLP body | ||
| # (token validation, variables fetch, CRUD endpoints). | ||
| pairs['service_instance_id'] = config._service_instance_id # pyright: ignore[reportPrivateUsage] | ||
|
|
||
| return pairs | ||
|
|
||
|
|
||
| def build_telemetry_header(config: LogfireConfig | None = None) -> str: | ||
| """Return the JSON-encoded value for the `X-Logfire-Telemetry` header.""" | ||
| pairs: dict[str, Any] = {**_base_telemetry_pairs()} | ||
| if config is not None: | ||
| pairs.update(_config_telemetry_pairs(config)) | ||
| return json.dumps(pairs, separators=(',', ':')) | ||
|
|
||
|
|
||
| def process_logfire_response_headers(response: requests.Response, *_args: Any, **_kwargs: Any) -> requests.Response: | ||
| """Handle `X-Logfire-Warning` / `X-Logfire-Error` headers on a Logfire API response. | ||
|
|
||
| Designed to be installed as a `requests` response hook | ||
| (`session.hooks['response'].append(...)`). | ||
| """ | ||
| warning_message = response.headers.get(WARNING_HEADER_NAME) | ||
| if warning_message: | ||
| warnings.warn(warning_message, LogfireServerWarning, stacklevel=2) | ||
| error_message = response.headers.get(ERROR_HEADER_NAME) | ||
| if error_message: | ||
| raise LogfireServerError(error_message) | ||
| return response | ||
|
|
||
|
|
||
| def install_logfire_response_hook(session: requests.Session) -> None: | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this seems like it should be a separate PR |
||
| """Install `process_logfire_response_headers` as a response hook on `session`. | ||
|
|
||
| `requests.Session()` always initialises `hooks['response']` to a list, and every | ||
| call site here passes a freshly-built session, so we just append. | ||
| """ | ||
| response_hooks: list[Any] = session.hooks.setdefault('response', []) | ||
| response_hooks.append(process_logfire_response_headers) | ||
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 |
|---|---|---|
| @@ -1,14 +1,13 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import platform | ||
| from datetime import datetime | ||
| from types import TracebackType | ||
| from typing import TYPE_CHECKING, Any, Generic, Literal, TypedDict, TypeVar | ||
|
|
||
| from typing_extensions import Self | ||
|
|
||
| from logfire import VERSION | ||
| from logfire._internal.config import get_base_url_from_token | ||
| from logfire._internal.telemetry_header import TELEMETRY_HEADER_NAME, build_telemetry_header | ||
|
|
||
| try: | ||
| from httpx import AsyncClient, Client, Response, Timeout | ||
|
|
@@ -87,7 +86,6 @@ def _rows_to_columns(result: RowQueryResults) -> QueryResults: | |
|
|
||
|
|
||
| _ACCEPT = Literal['application/json', 'application/vnd.apache.arrow.stream', 'text/csv'] | ||
| _USER_AGENT = f'logfire-sdk-python/{VERSION} (Python {platform.python_version()}, os {platform.platform()}, arch {platform.machine()})' | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why remove the user agent? Why not do the opposite and put everything in there? |
||
|
|
||
|
|
||
| class _BaseLogfireQueryClient(Generic[T]): | ||
|
|
@@ -97,7 +95,7 @@ def __init__(self, base_url: str, read_token: str, timeout: Timeout, client: typ | |
| self.timeout = timeout | ||
| headers = client_kwargs.pop('headers', {}) | ||
| headers['authorization'] = read_token | ||
| headers.setdefault('user-agent', _USER_AGENT) | ||
| headers[TELEMETRY_HEADER_NAME] = build_telemetry_header() | ||
| self.client: T = client(timeout=timeout, base_url=base_url, headers=headers, **client_kwargs) | ||
|
|
||
| def _build_query_params( | ||
|
|
||
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.