Repository navigation
Add resource_attributes and resource_detectors options to logfire.configure - #2012
Conversation
… resource-detectors
…tor precedence - Coerce a bare-string resource_detectors into a single-element list (e.g. 'host' -> ['host']) instead of raising, per review feedback. - Give OTEL_EXPERIMENTAL_RESOURCE_DETECTORS the lowest precedence: detectors passed explicitly via resource_detectors now override the env-var ones, while explicit attributes still win over both. Build the resource in three layers (env detectors < resource_detectors < explicit attributes).
Address review feedback (alexmojaki): - Remove the manual OTEL_RESOURCE_ATTRIBUTES re-parse. logfire.configure() attributes (service_name/version/environment, resource_attributes) now take precedence over OTEL_RESOURCE_ATTRIBUTES, and resource_detectors over OTEL_EXPERIMENTAL_RESOURCE_DETECTORS. This aligns with the OTel spec for OTEL_SERVICE_NAME (which now overrides service.name in OTEL_RESOURCE_ATTRIBUTES). - Keep the auto-detected git-hash service.version as a low-precedence fallback so it doesn't override an explicit OTEL_RESOURCE_ATTRIBUTES service.version. - Route resource_attributes/resource_detectors through param_manager.load_param, adding LOGFIRE_RESOURCE_ATTRIBUTES / LOGFIRE_RESOURCE_DETECTORS env vars and pyproject.toml support (dict[str,str] casting in ParamManager). Updates docs/docstrings and tests accordingly.
Per review feedback (alexmojaki + dmontagu): - An unknown resource detector name (from the resource_detectors kwarg, the LOGFIRE_RESOURCE_DETECTORS env var, or pyproject.toml) now emits a LogfireConfigWarning and is skipped rather than raising, so a typo can never crash the application. Matches OTel's tolerant handling of the env var. - Add the '*' name, which expands to every registered detector (except 'otel'), matching OTEL_EXPERIMENTAL_RESOURCE_DETECTORS. - Docs/docstring: lead with the 'process' detector example (host/os attributes are slated to be auto-set by the SDK in #2013) and document the new behaviour.
# Conflicts: # logfire/_internal/config.py # tests/test_configure.py
serialize_config() drops the git-detected service_version so child processes re-detect it as a low-precedence fallback, instead of treating it as explicit and overriding OTEL_RESOURCE_ATTRIBUTES (Devin review).
Refocus the section on the host.* attributes populated by default (and customizing host.name for the Hosts view), link to the Hosts page, and defer the resource_detectors/env-var reference detail to the logfire.configure() docstring (Alex review).
| 'api_key': False, | ||
| 'service_name': False, | ||
| 'service_version': True, | ||
| 'service_version': False, |
There was a problem hiding this comment.
Side effect of moving the git-hash service_version detection out of _load_configuration into _initialize (the refactor from the "this dance feels messy" thread). The git hash is no longer stored on the config object, so config.service_version is None when nothing was set explicitly, and this span field — bool(config.service_version) — now reflects whether a service_version was explicitly set rather than "a value exists including the git fallback". That is arguably the more useful signal, but happy to compute it differently (e.g. off the built resource) if you would rather it keep the old meaning.
There was a problem hiding this comment.
can _initialize set self.service_version?
There was a problem hiding this comment.
Done in faf8dd0 — _build_resource() now stores the git-hash fallback back on self.service_version (so the configuration span field and serialization reflect it again), while still applying it via the low-precedence fallback_resource_attributes so OTEL_RESOURCE_ATTRIBUTES keeps winning within the process. Updated test_configure_service_version and test_auto_detected_service_version_serialized to match, and the config-span snapshot back to service_version: True.
- Dedicated service_name/service_version/environment args now take precedence over the same keys set generically via resource_attributes (Alex review). - system-metrics docs: fix the dashboard instructions (the Basic System Metrics dashboard is a read-only standard dashboard, not customisable) and point to the Hosts view, Metrics explorer, Dashboards and Explore surfaces (Alex review). - SQL reference: expand the otel_resource_attributes section with code examples and a precise highest-to-lowest precedence list (Alex review). - Link to the OTel resource-detectors docs from the AdvancedOptions docstring (Alex review).
| 1. Attributes set explicitly in `logfire.configure()`: `resource_attributes`, and the dedicated `service_name` / `service_version` / `environment` arguments (which override the same keys set via `resource_attributes`). | ||
| 2. The `resource_detectors` argument. | ||
| 3. The standard `OTEL_RESOURCE_ATTRIBUTES` and `OTEL_EXPERIMENTAL_RESOURCE_DETECTORS` environment variables — also the mechanism used by other OpenTelemetry SDKs, e.g. `OTEL_RESOURCE_ATTRIBUTES=service.name=my-service,service.version=1.0.0`. |
There was a problem hiding this comment.
split 1 and 3 into pairs of items, also mention the LOGFIRE_ env vars
There was a problem hiding this comment.
Done in 6d6983f — split into one item per layer (dedicated args > resource_attributes > resource_detectors > OTEL_RESOURCE_ATTRIBUTES > OTEL_EXPERIMENTAL_RESOURCE_DETECTORS > defaults), noted the LOGFIRE_* env var / pyproject.toml equivalents for the first three, and added a line that items 4-5 are handled by OTel Resource.create (so OTEL_RESOURCE_ATTRIBUTES beating the env-var detectors matches stock OTel).
… on AdvancedOptions
…ce list - Restore the 'TODO use ProcessResourceDetector?' comment in common_resource_attributes (Alex review). - SQL reference: split the precedence list to one item per layer and note the LOGFIRE_*/pyproject equivalents; make explicit that OTEL_RESOURCE_ATTRIBUTES > OTEL_EXPERIMENTAL_RESOURCE_DETECTORS is handled by OpenTelemetry's Resource.create (so it matches stock OTel) (Alex review).
| You can also query the metrics directly in the [Explore](../guides/web-ui/explore.md) view via the `metrics` | ||
| table (see the [SQL reference](../reference/sql.md)). | ||
|
|
||
| ## Customising resource attributes |
There was a problem hiding this comment.
now this section can just very briefly mention host.name and then link to the SQL reference (with an anchor) which has plenty of detail.
There was a problem hiding this comment.
Done in faf8dd0 — trimmed this section to a one-line pointer (set a clearer host.name, or add other attributes such as process.*/cloud metadata) linking to the SQL reference #resource-attributes anchor, and dropped the redundant code sample.
|
|
||
| ### From a Python application | ||
|
|
||
| If your workload is a Python app already using Logfire, you can emit system metrics directly from the SDK with [`logfire.instrument_system_metrics()`](../../integrations/system-metrics.md) instead of (or alongside) running a collector. Logfire pre-populates the `host.name` resource attribute (overridable via `resource_attributes`), so the app's host shows up here automatically. |
There was a problem hiding this comment.
Done in faf8dd0 — added a link to the SQL reference next to the resource_attributes mention.
| } | ||
| if self.service_name: | ||
| # When unset, `Resource.create` below applies its own `unknown_service` default. | ||
| otel_resource_attributes['service.name'] = self.service_name |
There was a problem hiding this comment.
emit a warning when any of the specific arguments like service_name overrides self.resource_attributes. do it in a DRY way.
There was a problem hiding this comment.
Done in faf8dd0 — _build_resource() collects the dedicated args into a dedicated_attributes dict and warns once per key (single loop) when it overrides a different value the user also set via resource_attributes. Covered by the updated test_dedicated_args_take_precedence_over_resource_attributes.
| # Explicit `logfire.configure()` attributes (logfire's own plus the `resource_attributes` | ||
| # argument) take precedence over everything detected above, including the env vars | ||
| # `OTEL_RESOURCE_ATTRIBUTES` and `OTEL_EXPERIMENTAL_RESOURCE_DETECTORS`. | ||
| resource = resource.merge(Resource(otel_resource_attributes)) |
There was a problem hiding this comment.
move the whole resource construction to a method
There was a problem hiding this comment.
Done in faf8dd0 — extracted the whole resource construction into LogfireConfig._build_resource(); _initialize now just does resource = self._build_resource().
| def _load_resource_detector_entry_point(entry_point: Any, result: list[ResourceDetector]) -> None: | ||
| try: | ||
| result.append(entry_point.load()()) | ||
| except Exception as exc: # pragma: no cover |
There was a problem hiding this comment.
Good catch — the pragma was hiding an untested branch. Removed it and added test_resource_detector_load_failure, which patches entry_points with a detector that raises on load and asserts the warning fires and configuration still succeeds.
| def _load_resource_detector_entry_point(entry_point: Any, result: list[ResourceDetector]) -> None: | ||
| try: | ||
| result.append(entry_point.load()()) |
There was a problem hiding this comment.
| def _load_resource_detector_entry_point(entry_point: Any, result: list[ResourceDetector]) -> None: | |
| try: | |
| result.append(entry_point.load()()) | |
| def _load_resource_detector_entry_point(entry_point: Any): | |
| try: | |
| return entry_point.load()() |
There was a problem hiding this comment.
is the type really unknown?
There was a problem hiding this comment.
Done in faf8dd0 — _load_resource_detector_entry_point now returns ResourceDetector | None (callers append when non-None) instead of mutating a result list. And no, the type wasn't really unknown — annotated it as importlib.metadata.EntryPoint.
… _build_resource - _build_resource(): move the whole resource construction out of _initialize into a dedicated method (alexmojaki). - Store the git-hash service_version fallback back on self.service_version so it's reflected in the configuration span and serialized to child processes, while keeping it a low-precedence default within the process (alexmojaki). - Warn (DRY) when a dedicated argument (service_name/service_version/environment/ code_source) overrides a different value also set via resource_attributes. - _load_resource_detector_entry_point now returns the detector (typed EntryPoint) instead of mutating a list, and drops the no-longer-needed `# pragma: no cover` (covered by new test_resource_detector_load_failure). - Link the resource_attributes / resource_detectors docstrings and the system-metrics / hosts docs to the SQL reference; trim the system-metrics "Customising resource attributes" section to a brief pointer.
Docs Preview
Re-add the |
📝 WalkthroughWalkthroughThis PR adds 🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
docs/reference/sql.md (1)
271-278: ⚡ Quick winDocument the resource detector wildcard syntax.
The
'*'wildcard (which expands to all registered detectors except'otel') is part of the public API per the PR objectives but isn't mentioned here. A brief example would help:# Instead of listing individual detectors: advanced=logfire.AdvancedOptions(resource_detectors=['process', 'host', 'os']), # Run all registered detectors (except otel, which Resource.create handles): advanced=logfire.AdvancedOptions(resource_detectors=['*']),🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/reference/sql.md` around lines 271 - 278, The documentation for the logfire.configure() function with resource_detectors parameter is missing information about the wildcard syntax. Add a documented example showing that the `'*'` wildcard can be used in the resource_detectors list to automatically include all registered detectors except 'otel', providing this as a convenient alternative to manually listing individual detectors like 'process', 'host', and 'os'. Include a brief comment explaining that this wildcard expands to all registered detectors.tests/test_configure.py (1)
1073-1075: ⚡ Quick winStrengthen this test by asserting
entry_points()call arguments.The patch currently returns a failing entry point for any call shape; asserting the call arguments will lock the test to the intended lookup contract.
Suggested fix
- with patch('logfire._internal.config.entry_points', return_value=[FailingEntryPoint()]): + with patch('logfire._internal.config.entry_points', return_value=[FailingEntryPoint()]) as entry_points_mock: with pytest.warns(LogfireConfigWarning, match="Failed to load resource detector 'failing': boom"): configure(**config_kwargs) + entry_points_mock.assert_called_with(group='opentelemetry_resource_detector', name='failing')🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/test_configure.py` around lines 1073 - 1075, The test should verify not only that the warning is raised but also that entry_points() is called with the correct arguments. Currently, the patch will return the failing entry point for any call shape. To strengthen the test, capture the mock object returned by the patch on entry_points and add an assertion after the configure call to verify that entry_points was called with the expected arguments (the group name for resource detectors). This locks the test to validate the intended lookup contract and ensures the code is calling entry_points correctly.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@tests/test_configure.py`:
- Around line 768-772: The test_configure_service_version function
unconditionally executes a git command via subprocess.check_output which will
fail if git is unavailable or the checkout is not a git repository, causing the
test to fail before reaching the actual feature assertions. Wrap the
subprocess.check_output call that retrieves the git SHA in a try-except block to
handle subprocess exceptions, and either skip the test gracefully using
pytest.skip when git is unavailable or provide a fallback value for the git_sha
variable. Apply the same fix to the other instance mentioned at line 1185 that
also calls git rev-parse HEAD.
---
Nitpick comments:
In `@docs/reference/sql.md`:
- Around line 271-278: The documentation for the logfire.configure() function
with resource_detectors parameter is missing information about the wildcard
syntax. Add a documented example showing that the `'*'` wildcard can be used in
the resource_detectors list to automatically include all registered detectors
except 'otel', providing this as a convenient alternative to manually listing
individual detectors like 'process', 'host', and 'os'. Include a brief comment
explaining that this wildcard expands to all registered detectors.
In `@tests/test_configure.py`:
- Around line 1073-1075: The test should verify not only that the warning is
raised but also that entry_points() is called with the correct arguments.
Currently, the patch will return the failing entry point for any call shape. To
strengthen the test, capture the mock object returned by the patch on
entry_points and add an assertion after the configure call to verify that
entry_points was called with the expected arguments (the group name for resource
detectors). This locks the test to validate the intended lookup contract and
ensures the code is calling entry_points correctly.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: a631efd1-9c7a-4ef5-9d46-08ba8aff456e
📒 Files selected for processing (6)
docs/guides/web-ui/hosts.mddocs/integrations/system-metrics.mddocs/reference/sql.mdlogfire/_internal/config.pylogfire/_internal/config_params.pytests/test_configure.py
Context
The (beta) Hosts view needs the
host.nameresource attribute to associate telemetry with a machine, and more generally there was no programmatic way to shape resource attributes fromlogfire.configure()— the only options were theOTEL_RESOURCE_ATTRIBUTES/OTEL_EXPERIMENTAL_RESOURCE_DETECTORSenv vars.This PR builds on #2013 (now merged), which pre-populates
host.*/os.*/process.runtime.*by default so machines show up in the Hosts view out of the box, and adds first-class, programmatic control over the resource.What this PR adds
resource_attributes(top-levellogfire.configure()argument): a static mapping of extra resource attributes, e.g. to override the auto-detectedhost.nameor add custom attributes — a programmatic alternative toOTEL_RESOURCE_ATTRIBUTES.resource_detectors(onAdvancedOptions): OpenTelemetry resource detectors to run when building the resource. Each item is aResourceDetectorinstance or the name of a detector registered under the standardopentelemetry_resource_detectorentry-point group (so third-party detector packages work too).opentelemetry-sdkprovides'os','host', and'process'; the special name'*'runs every registered detector. Sinceos.*/host.*are already populated by default,'process'is the main one you'd add.LOGFIRE_RESOURCE_ATTRIBUTES,LOGFIRE_RESOURCE_DETECTORS) andpyproject.tomlunder[tool.logfire].Precedence
Resource attributes are merged from lowest to highest precedence:
process.runtime.*,host.*,os.*, a randomservice.instance.id, and the git-hashservice.versionfallback. These deliberately sit below the env vars so they can be overridden.OTEL_RESOURCE_ATTRIBUTESandOTEL_EXPERIMENTAL_RESOURCE_DETECTORS(applied byResource.create).resource_detectorsargument.logfire.configure()attributes —resource_attributes,service_name/service_version/environment, etc.So explicit
logfire.configure()settings win over everything, theresource_detectorsargument beats the env-var detectors, andOTEL_RESOURCE_ATTRIBUTESstill overrides the auto-detected defaults (e.g. a customer whosesocket.gethostname()is a useless container ID can overridehost.namecleanly).Design notes
get_aggregated_resources()plus entry-point loading, rather than writing env vars — there's a clean programmatic path, so no global-state mutation, andResourceDetectorinstances are supported, not just names.LogfireConfigWarningand is skipped rather than raising, so a typo can never crash the app — matching OTel's tolerant handling of the env var.service.versionfallback is now resolved in_initialize(where the resource is built) instead of_load_configuration(which runs at import). This removes agitsubprocess call onimport logfire, keeps the git hash as a low-precedence fallback thatOTEL_RESOURCE_ATTRIBUTEScan override, and — because it's never stored on the config — means child processes (ProcessPoolExecutor) re-detect it as a fallback rather than treating it as an explicit value.resource_detectorslives onAdvancedOptionsbecause it's a niche option (the commonos/hostattributes are populated by default), whileresource_attributesstays top-level since overridinghost.name/ adding custom attributes is a common need.Platform-side note (not addressed here): the default
base='basic'config doesn't emitsystem.cpu.utilization— its CPU metric is the logfire-specificsystem.cpu.simple_utilization, which the Hosts page queries don't currently include — so basic-config hosts appear (viasystem.memory.utilization) but with an empty CPU column.Docs
otel_resource_attributescolumn.Checklist
'*', bare-string coercion, unknown-name warning, precedence vs env vars, env var +pyproject.toml), default host/os population and env-var override, git-hash fallback + serialization to child processes.logfire-apishim needs no changes (itsconfigureaccepts**kwargs;.pyistubs are regenerated at release).