Buckets:

download
raw
156 kB
from __future__ import annotations import dataclasses import getpass import inspect import json import os import pickle import signal import subprocess import sys import threading import warnings from collections.abc import Callable, Iterable, Sequence from contextlib import ExitStack from io import StringIO from pathlib import Path from time import sleep, time from typing import Any from unittest import mock from unittest.mock import call, patch import inline_snapshot.extra import pytest import requests.exceptions import requests_mock from dirty_equals import IsPartialDict, IsStr from inline_snapshot import snapshot from opentelemetry._logs import LogRecord, get_logger, get_logger_provider from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter from opentelemetry.metrics import NoOpMeterProvider, get_meter_provider from opentelemetry.propagate import get_global_textmap from opentelemetry.propagators.composite import CompositePropagator from opentelemetry.sdk._logs import LogRecordProcessor from opentelemetry.sdk._logs._internal import SynchronousMultiLogRecordProcessor from opentelemetry.sdk._logs.export import BatchLogRecordProcessor, LogRecordExporter, SimpleLogRecordProcessor from opentelemetry.sdk.metrics.export import InMemoryMetricReader, PeriodicExportingMetricReader from opentelemetry.sdk.resources import Resource, ResourceDetector from opentelemetry.sdk.trace import ReadableSpan, SpanProcessor, SynchronousMultiSpanProcessor from opentelemetry.sdk.trace.export import ( BatchSpanProcessor, ConsoleSpanExporter, SimpleSpanProcessor, SpanExporter, SpanExportResult, ) from opentelemetry.trace import get_tracer_provider from pydantic import __version__ as pydantic_version from pytest import LogCaptureFixture import logfire import logfire._internal.config as config_module from logfire import configure, propagate from logfire._internal.baggage import DirectBaggageAttributesSpanProcessor from logfire._internal.config import ( GLOBAL_CONFIG, CodeSource, ConsoleOptions, LogfireConfig, LogfireConfigWarning, LogfireCredentials, VariablesOptions, get_base_url_from_token, sanitize_project_name, ) from logfire._internal.config_params import extract_list_of_str, normalize_token from logfire._internal.exporters.console import ( ConsoleLogExporter, ShowParentsConsoleSpanExporter, SimpleConsoleSpanExporter, ) from logfire._internal.exporters.dynamic_batch import DynamicBatchSpanProcessor from logfire._internal.exporters.logs import CheckSuppressInstrumentationLogProcessorWrapper, MainLogProcessorWrapper from logfire._internal.exporters.otlp import QuietLogExporter, QuietSpanExporter from logfire._internal.exporters.processor_wrapper import ( CheckSuppressInstrumentationProcessorWrapper, MainSpanProcessorWrapper, ) from logfire._internal.exporters.quiet_metrics import QuietMetricExporter from logfire._internal.exporters.remove_pending import RemovePendingSpansExporter from logfire._internal.forwarding import OTLPForwardingManager from logfire._internal.integrations.executors import deserialize_config, serialize_config from logfire._internal.interactive import NonInteractiveError from logfire._internal.tracer import PendingSpanProcessor from logfire._internal.utils import SeededRandomIdGenerator, get_version from logfire.exceptions import LogfireConfigError from logfire.integrations.pydantic import get_pydantic_plugin_config from logfire.propagate import NoExtractTraceContextPropagator, WarnOnExtractTraceContextPropagator from logfire.testing import TestExporter, TestLogExporter from logfire.version import VERSION PROCESS_RUNTIME_VERSION_REGEX = r'(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)' @pytest.fixture(autouse=True) def no_log_on_config(config: None, caplog: pytest.LogCaptureFixture) -> None: assert not caplog.messages def test_propagate_config_to_tags(exporter: TestExporter) -> None: tags1 = logfire.with_tags('tag1', 'tag2') tags2 = logfire.with_tags('tag3', 'tag4') for lf in (logfire, tags1, tags2): with lf.span('root'): with lf.span('child'): logfire.info('test1') tags1.info('test2') tags2.info('test3') assert exporter.exported_spans_as_dict(_include_pending_spans=True) == snapshot( [ { 'name': 'root', 'context': {'trace_id': 1, 'span_id': 2, 'is_remote': False}, 'parent': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'start_time': 1000000000, 'end_time': 1000000000, 'attributes': { 'code.filepath': 'test_configure.py', 'code.lineno': 123, 'code.function': 'test_propagate_config_to_tags', 'logfire.msg_template': 'root', 'logfire.msg': 'root', 'logfire.span_type': 'pending_span', 'logfire.pending_parent_id': '0000000000000000', }, }, { 'name': 'child', 'context': {'trace_id': 1, 'span_id': 4, 'is_remote': False}, 'parent': {'trace_id': 1, 'span_id': 3, 'is_remote': False}, 'start_time': 2000000000, 'end_time': 2000000000, 'attributes': { 'code.filepath': 'test_configure.py', 'code.lineno': 123, 'code.function': 'test_propagate_config_to_tags', 'logfire.msg_template': 'child', 'logfire.msg': 'child', 'logfire.span_type': 'pending_span', 'logfire.pending_parent_id': '0000000000000001', }, }, { 'name': 'test1', 'context': {'trace_id': 1, 'span_id': 5, 'is_remote': False}, 'parent': {'trace_id': 1, 'span_id': 3, 'is_remote': False}, 'start_time': 3000000000, 'end_time': 3000000000, 'attributes': { 'logfire.span_type': 'log', 'logfire.level_num': 9, 'logfire.msg_template': 'test1', 'logfire.msg': 'test1', 'code.filepath': 'test_configure.py', 'code.lineno': 123, 'code.function': 'test_propagate_config_to_tags', }, }, { 'name': 'test2', 'context': {'trace_id': 1, 'span_id': 6, 'is_remote': False}, 'parent': {'trace_id': 1, 'span_id': 3, 'is_remote': False}, 'start_time': 4000000000, 'end_time': 4000000000, 'attributes': { 'logfire.span_type': 'log', 'logfire.level_num': 9, 'logfire.msg_template': 'test2', 'logfire.msg': 'test2', 'code.filepath': 'test_configure.py', 'code.lineno': 123, 'code.function': 'test_propagate_config_to_tags', 'logfire.tags': ('tag1', 'tag2'), }, }, { 'name': 'test3', 'context': {'trace_id': 1, 'span_id': 7, 'is_remote': False}, 'parent': {'trace_id': 1, 'span_id': 3, 'is_remote': False}, 'start_time': 5000000000, 'end_time': 5000000000, 'attributes': { 'logfire.span_type': 'log', 'logfire.level_num': 9, 'logfire.msg_template': 'test3', 'logfire.msg': 'test3', 'code.filepath': 'test_configure.py', 'code.lineno': 123, 'code.function': 'test_propagate_config_to_tags', 'logfire.tags': ('tag3', 'tag4'), }, }, { 'name': 'child', 'context': {'trace_id': 1, 'span_id': 3, 'is_remote': False}, 'parent': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'start_time': 2000000000, 'end_time': 6000000000, 'attributes': { 'code.filepath': 'test_configure.py', 'code.lineno': 123, 'code.function': 'test_propagate_config_to_tags', 'logfire.msg_template': 'child', 'logfire.span_type': 'span', 'logfire.msg': 'child', }, }, { 'name': 'root', 'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'parent': None, 'start_time': 1000000000, 'end_time': 7000000000, 'attributes': { 'code.filepath': 'test_configure.py', 'code.lineno': 123, 'code.function': 'test_propagate_config_to_tags', 'logfire.msg_template': 'root', 'logfire.span_type': 'span', 'logfire.msg': 'root', }, }, { 'name': 'root', 'context': {'trace_id': 2, 'span_id': 9, 'is_remote': False}, 'parent': {'trace_id': 2, 'span_id': 8, 'is_remote': False}, 'start_time': 8000000000, 'end_time': 8000000000, 'attributes': { 'code.filepath': 'test_configure.py', 'code.lineno': 123, 'code.function': 'test_propagate_config_to_tags', 'logfire.msg_template': 'root', 'logfire.msg': 'root', 'logfire.tags': ('tag1', 'tag2'), 'logfire.span_type': 'pending_span', 'logfire.pending_parent_id': '0000000000000000', }, }, { 'name': 'child', 'context': {'trace_id': 2, 'span_id': 11, 'is_remote': False}, 'parent': {'trace_id': 2, 'span_id': 10, 'is_remote': False}, 'start_time': 9000000000, 'end_time': 9000000000, 'attributes': { 'code.filepath': 'test_configure.py', 'code.lineno': 123, 'code.function': 'test_propagate_config_to_tags', 'logfire.msg_template': 'child', 'logfire.msg': 'child', 'logfire.tags': ('tag1', 'tag2'), 'logfire.span_type': 'pending_span', 'logfire.pending_parent_id': '0000000000000008', }, }, { 'name': 'test1', 'context': {'trace_id': 2, 'span_id': 12, 'is_remote': False}, 'parent': {'trace_id': 2, 'span_id': 10, 'is_remote': False}, 'start_time': 10000000000, 'end_time': 10000000000, 'attributes': { 'logfire.span_type': 'log', 'logfire.level_num': 9, 'logfire.msg_template': 'test1', 'logfire.msg': 'test1', 'code.filepath': 'test_configure.py', 'code.lineno': 123, 'code.function': 'test_propagate_config_to_tags', }, }, { 'name': 'test2', 'context': {'trace_id': 2, 'span_id': 13, 'is_remote': False}, 'parent': {'trace_id': 2, 'span_id': 10, 'is_remote': False}, 'start_time': 11000000000, 'end_time': 11000000000, 'attributes': { 'logfire.span_type': 'log', 'logfire.level_num': 9, 'logfire.msg_template': 'test2', 'logfire.msg': 'test2', 'code.filepath': 'test_configure.py', 'code.lineno': 123, 'code.function': 'test_propagate_config_to_tags', 'logfire.tags': ('tag1', 'tag2'), }, }, { 'name': 'test3', 'context': {'trace_id': 2, 'span_id': 14, 'is_remote': False}, 'parent': {'trace_id': 2, 'span_id': 10, 'is_remote': False}, 'start_time': 12000000000, 'end_time': 12000000000, 'attributes': { 'logfire.span_type': 'log', 'logfire.level_num': 9, 'logfire.msg_template': 'test3', 'logfire.msg': 'test3', 'code.filepath': 'test_configure.py', 'code.lineno': 123, 'code.function': 'test_propagate_config_to_tags', 'logfire.tags': ('tag3', 'tag4'), }, }, { 'name': 'child', 'context': {'trace_id': 2, 'span_id': 10, 'is_remote': False}, 'parent': {'trace_id': 2, 'span_id': 8, 'is_remote': False}, 'start_time': 9000000000, 'end_time': 13000000000, 'attributes': { 'code.filepath': 'test_configure.py', 'code.lineno': 123, 'code.function': 'test_propagate_config_to_tags', 'logfire.msg_template': 'child', 'logfire.tags': ('tag1', 'tag2'), 'logfire.span_type': 'span', 'logfire.msg': 'child', }, }, { 'name': 'root', 'context': {'trace_id': 2, 'span_id': 8, 'is_remote': False}, 'parent': None, 'start_time': 8000000000, 'end_time': 14000000000, 'attributes': { 'code.filepath': 'test_configure.py', 'code.lineno': 123, 'code.function': 'test_propagate_config_to_tags', 'logfire.msg_template': 'root', 'logfire.tags': ('tag1', 'tag2'), 'logfire.span_type': 'span', 'logfire.msg': 'root', }, }, { 'name': 'root', 'context': {'trace_id': 3, 'span_id': 16, 'is_remote': False}, 'parent': {'trace_id': 3, 'span_id': 15, 'is_remote': False}, 'start_time': 15000000000, 'end_time': 15000000000, 'attributes': { 'code.filepath': 'test_configure.py', 'code.lineno': 123, 'code.function': 'test_propagate_config_to_tags', 'logfire.msg_template': 'root', 'logfire.msg': 'root', 'logfire.tags': ('tag3', 'tag4'), 'logfire.span_type': 'pending_span', 'logfire.pending_parent_id': '0000000000000000', }, }, { 'name': 'child', 'context': {'trace_id': 3, 'span_id': 18, 'is_remote': False}, 'parent': {'trace_id': 3, 'span_id': 17, 'is_remote': False}, 'start_time': 16000000000, 'end_time': 16000000000, 'attributes': { 'code.filepath': 'test_configure.py', 'code.lineno': 123, 'code.function': 'test_propagate_config_to_tags', 'logfire.msg_template': 'child', 'logfire.msg': 'child', 'logfire.tags': ('tag3', 'tag4'), 'logfire.span_type': 'pending_span', 'logfire.pending_parent_id': '000000000000000f', }, }, { 'name': 'test1', 'context': {'trace_id': 3, 'span_id': 19, 'is_remote': False}, 'parent': {'trace_id': 3, 'span_id': 17, 'is_remote': False}, 'start_time': 17000000000, 'end_time': 17000000000, 'attributes': { 'logfire.span_type': 'log', 'logfire.level_num': 9, 'logfire.msg_template': 'test1', 'logfire.msg': 'test1', 'code.filepath': 'test_configure.py', 'code.lineno': 123, 'code.function': 'test_propagate_config_to_tags', }, }, { 'name': 'test2', 'context': {'trace_id': 3, 'span_id': 20, 'is_remote': False}, 'parent': {'trace_id': 3, 'span_id': 17, 'is_remote': False}, 'start_time': 18000000000, 'end_time': 18000000000, 'attributes': { 'logfire.span_type': 'log', 'logfire.level_num': 9, 'logfire.msg_template': 'test2', 'logfire.msg': 'test2', 'code.filepath': 'test_configure.py', 'code.lineno': 123, 'code.function': 'test_propagate_config_to_tags', 'logfire.tags': ('tag1', 'tag2'), }, }, { 'name': 'test3', 'context': {'trace_id': 3, 'span_id': 21, 'is_remote': False}, 'parent': {'trace_id': 3, 'span_id': 17, 'is_remote': False}, 'start_time': 19000000000, 'end_time': 19000000000, 'attributes': { 'logfire.span_type': 'log', 'logfire.level_num': 9, 'logfire.msg_template': 'test3', 'logfire.msg': 'test3', 'code.filepath': 'test_configure.py', 'code.lineno': 123, 'code.function': 'test_propagate_config_to_tags', 'logfire.tags': ('tag3', 'tag4'), }, }, { 'name': 'child', 'context': {'trace_id': 3, 'span_id': 17, 'is_remote': False}, 'parent': {'trace_id': 3, 'span_id': 15, 'is_remote': False}, 'start_time': 16000000000, 'end_time': 20000000000, 'attributes': { 'code.filepath': 'test_configure.py', 'code.lineno': 123, 'code.function': 'test_propagate_config_to_tags', 'logfire.msg_template': 'child', 'logfire.tags': ('tag3', 'tag4'), 'logfire.span_type': 'span', 'logfire.msg': 'child', }, }, { 'name': 'root', 'context': {'trace_id': 3, 'span_id': 15, 'is_remote': False}, 'parent': None, 'start_time': 15000000000, 'end_time': 21000000000, 'attributes': { 'code.filepath': 'test_configure.py', 'code.lineno': 123, 'code.function': 'test_propagate_config_to_tags', 'logfire.msg_template': 'root', 'logfire.tags': ('tag3', 'tag4'), 'logfire.span_type': 'span', 'logfire.msg': 'root', }, }, ] ) def fresh_pydantic_plugin(): GLOBAL_CONFIG.param_manager.__dict__.pop('pydantic_plugin', None) # reset the cached_property return get_pydantic_plugin_config() @pytest.mark.skipif( get_version(pydantic_version) < get_version('2.5.0'), reason='skipping for pydantic versions < v2.5' ) def test_pydantic_plugin_include_exclude_strings(): logfire.instrument_pydantic(include='inc', exclude='exc') assert fresh_pydantic_plugin().include == {'inc'} assert fresh_pydantic_plugin().exclude == {'exc'} def test_read_config_from_environment_variables() -> None: assert fresh_pydantic_plugin().record == 'off' with patch.dict(os.environ, {'LOGFIRE_PYDANTIC_PLUGIN_RECORD': 'all'}): assert fresh_pydantic_plugin().record == 'all' with patch.dict(os.environ, {'LOGFIRE_PYDANTIC_PLUGIN_RECORD': 'test'}): with pytest.raises( LogfireConfigError, match="Expected pydantic_plugin_record to be one of \\('off', 'all', 'failure', 'metrics'\\), got 'test'", ): fresh_pydantic_plugin() with patch.dict(os.environ, {'LOGFIRE_SEND_TO_LOGFIRE': 'not-valid'}): with inline_snapshot.extra.raises( snapshot( "LogfireConfigError: Expected send_to_logfire to be an instance of one of (<class 'bool'>, typing.Literal['if-token-present']), got 'not-valid'" ) ): configure() assert fresh_pydantic_plugin().include == set() with patch.dict(os.environ, {'LOGFIRE_PYDANTIC_PLUGIN_INCLUDE': 'test'}): assert fresh_pydantic_plugin().include == {'test'} with patch.dict(os.environ, {'LOGFIRE_PYDANTIC_PLUGIN_INCLUDE': 'test1, test2'}): assert fresh_pydantic_plugin().include == {'test1', 'test2'} assert fresh_pydantic_plugin().exclude == set() with patch.dict(os.environ, {'LOGFIRE_PYDANTIC_PLUGIN_EXCLUDE': 'test'}): assert fresh_pydantic_plugin().exclude == {'test'} with patch.dict(os.environ, {'LOGFIRE_PYDANTIC_PLUGIN_EXCLUDE': 'test1, test2'}): assert fresh_pydantic_plugin().exclude == {'test1', 'test2'} def test_read_config_from_pyproject_toml(tmp_path: Path) -> None: (tmp_path / 'pyproject.toml').write_text( f""" [tool.logfire] base_url = "https://api.logfire.io" send_to_logfire = false project_name = "test" console_colors = "never" console_include_timestamp = false console_include_tags = false data_dir = "{tmp_path}" pydantic_plugin_record = "metrics" pydantic_plugin_include = " test1, test2" pydantic_plugin_exclude = "test3 ,test4" trace_sample_rate = "0.123" """ ) configure(config_dir=tmp_path) assert GLOBAL_CONFIG.advanced.base_url == 'https://api.logfire.io' assert GLOBAL_CONFIG.send_to_logfire is False assert GLOBAL_CONFIG.console assert GLOBAL_CONFIG.console.colors == 'never' assert GLOBAL_CONFIG.console.include_timestamps is False assert GLOBAL_CONFIG.console.include_tags is False assert GLOBAL_CONFIG.data_dir == tmp_path assert fresh_pydantic_plugin().record == 'metrics' assert fresh_pydantic_plugin().include == {'test1', 'test2'} assert fresh_pydantic_plugin().exclude == {'test3', 'test4'} assert GLOBAL_CONFIG.sampling.head == 0.123 def test_logfire_invalid_config_dir(tmp_path: Path): (tmp_path / 'pyproject.toml').write_text('invalid-data') with pytest.raises( LogfireConfigError, match='Invalid config file:', ): LogfireConfig(config_dir=tmp_path) def test_logfire_config_console_options() -> None: assert LogfireConfig().console == ConsoleOptions() assert LogfireConfig(console=False).console is False assert LogfireConfig(console=ConsoleOptions(colors='never', verbose=True)).console == ConsoleOptions( colors='never', verbose=True ) with patch.dict(os.environ, {'LOGFIRE_CONSOLE': 'false'}): assert LogfireConfig().console is False with patch.dict(os.environ, {'LOGFIRE_CONSOLE': 'true'}): assert LogfireConfig().console == ConsoleOptions( colors='auto', span_style='show-parents', include_timestamps=True, verbose=False ) with patch.dict(os.environ, {'LOGFIRE_CONSOLE_COLORS': 'never'}): assert LogfireConfig().console == ConsoleOptions(colors='never') with patch.dict(os.environ, {'LOGFIRE_CONSOLE_COLORS': 'test'}): with pytest.raises( LogfireConfigError, match="Expected console_colors to be one of \\('auto', 'always', 'never'\\), got 'test'", ): LogfireConfig() with patch.dict(os.environ, {'LOGFIRE_CONSOLE_VERBOSE': '1'}): assert LogfireConfig().console == ConsoleOptions(verbose=True) with patch.dict(os.environ, {'LOGFIRE_CONSOLE_VERBOSE': 'false'}): assert LogfireConfig().console == ConsoleOptions(verbose=False) def test_logfire_config_reconfigure_replaces_forwarding_manager() -> None: config = logfire.DEFAULT_LOGFIRE_INSTANCE.config previous_manager = config._otlp_forwarding # pyright: ignore[reportPrivateUsage] assert isinstance(previous_manager, OTLPForwardingManager) assert previous_manager.has_destinations() is False logfire.configure(send_to_logfire=False, console=False, metrics=False) manager = config._otlp_forwarding # pyright: ignore[reportPrivateUsage] assert isinstance(manager, OTLPForwardingManager) assert manager is not previous_manager assert previous_manager.closed is True assert manager.has_destinations() is False def test_forwarding_destinations_registered_from_active_logfire_tokens(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(LogfireConfig, '_initialize_credentials_from_token', lambda *args: None) # type: ignore configure( token=['pylf_v1_us_token1', 'pylf_v1_us_token2', 'pylf_v1_eu_token3'], send_to_logfire=True, console=False, metrics=False, ) wait_for_check_token_thread() manager = GLOBAL_CONFIG._otlp_forwarding # pyright: ignore[reportPrivateUsage] assert set(manager.pipelines) == {'https://logfire-us.pydantic.dev', 'https://logfire-eu.pydantic.dev'} assert manager.pipelines['https://logfire-us.pydantic.dev'].tokens == [ 'pylf_v1_us_token1', 'pylf_v1_us_token2', ] assert manager.pipelines['https://logfire-eu.pydantic.dev'].tokens == ['pylf_v1_eu_token3'] def test_forwarding_destinations_not_registered_when_send_to_logfire_false() -> None: logfire.configure(token='pylf_v1_us_token', send_to_logfire=False, console=False, metrics=False) config = logfire.DEFAULT_LOGFIRE_INSTANCE.config manager = config._otlp_forwarding # pyright: ignore[reportPrivateUsage] assert manager.has_destinations() is False def test_shutdown_otlp_forwarding_closes_local_forwarding_managers( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr(LogfireConfig, '_initialize_credentials_from_token', lambda *args: None) # type: ignore local_logfires = [ logfire.configure(local=True, token='pylf_v1_us_token1', send_to_logfire=True, console=False, metrics=False), logfire.configure(local=True, token='pylf_v1_eu_token2', send_to_logfire=True, console=False, metrics=False), ] wait_for_check_token_thread() managers = [local_logfire.config._otlp_forwarding for local_logfire in local_logfires] # pyright: ignore[reportPrivateUsage] try: assert all(manager.has_destinations() for manager in managers) config_module.shutdown_otlp_forwarding(100) assert all(manager.closed for manager in managers) assert all(pipeline.closed for manager in managers for pipeline in manager.pipelines.values()) finally: for local_logfire in local_logfires: local_logfire.shutdown(flush=False) @pytest.mark.parametrize('flush', [False, True]) def test_logfire_shutdown_closes_providers(monkeypatch: pytest.MonkeyPatch, flush: bool) -> None: config = logfire.DEFAULT_LOGFIRE_INSTANCE.config variable_provider = mock.Mock() otlp_forwarding = mock.Mock() otlp_forwarding.shutdown.return_value = True tracer_provider = mock.Mock() logger_provider = mock.Mock() meter_provider = mock.Mock() monkeypatch.setattr(config, '_variable_provider', variable_provider) monkeypatch.setattr(config, '_otlp_forwarding', otlp_forwarding) monkeypatch.setattr(config, '_tracer_provider', tracer_provider) monkeypatch.setattr(config, '_logger_provider', logger_provider) monkeypatch.setattr(config, '_meter_provider', meter_provider) assert logfire.shutdown(timeout_millis=1000, flush=flush) is True forwarding_timeout = otlp_forwarding.shutdown.call_args.args[0] otlp_forwarding.shutdown.assert_called_once_with(forwarding_timeout, drain_queued=flush) if flush: tracer_provider.force_flush.assert_called_once() logger_provider.force_flush.assert_called_once() meter_provider.force_flush.assert_called_once() else: tracer_provider.force_flush.assert_not_called() logger_provider.force_flush.assert_not_called() meter_provider.force_flush.assert_not_called() tracer_provider.shutdown.assert_called_once() logger_provider.shutdown.assert_called_once() meter_provider.shutdown.assert_called_once() @pytest.mark.parametrize( ('logger_result', 'forwarding_result', 'tracer_result', 'expected'), [ (True, True, True, True), (None, True, True, True), (False, True, True, False), (True, False, True, False), (True, True, False, False), ], ) def test_force_flush_combines_provider_results( monkeypatch: pytest.MonkeyPatch, logger_result: bool | None, forwarding_result: bool, tracer_result: bool, expected: bool, ) -> None: config = logfire.DEFAULT_LOGFIRE_INSTANCE.config meter_provider = mock.Mock() logger_provider = mock.Mock() logger_provider.force_flush.return_value = logger_result otlp_forwarding = mock.Mock() otlp_forwarding.force_flush.return_value = forwarding_result tracer_provider = mock.Mock() tracer_provider.force_flush.return_value = tracer_result monkeypatch.setattr(config, '_meter_provider', meter_provider) monkeypatch.setattr(config, '_logger_provider', logger_provider) monkeypatch.setattr(config, '_otlp_forwarding', otlp_forwarding) monkeypatch.setattr(config, '_tracer_provider', tracer_provider) assert config.force_flush(123) is expected meter_provider.force_flush.assert_called_once_with(123) logger_provider.force_flush.assert_called_once_with(123) otlp_forwarding.force_flush.assert_called_once_with(123) tracer_provider.force_flush.assert_called_once_with(123) def get_batch_span_exporter(processor: SpanProcessor) -> SpanExporter: assert isinstance(processor, BatchSpanProcessor) try: exporter = processor.span_exporter except AttributeError: # pragma: no cover exporter = processor._batch_processor._exporter # type: ignore return exporter # type: ignore def get_batch_log_exporter(processor: LogRecordProcessor) -> LogRecordExporter: assert isinstance(processor, BatchLogRecordProcessor) return processor._batch_processor._exporter # type: ignore def test_configure_export_delay() -> None: class TrackingExporter(SpanExporter): def __init__(self) -> None: self.last_export_timestamp: float | None = None self.export_delays: list[float] = [] def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult: t = time() if self.last_export_timestamp is not None: self.export_delays.append(t - self.last_export_timestamp) self.last_export_timestamp = t return SpanExportResult.SUCCESS def configure_tracking_exporter(): request_mocker = requests_mock.Mocker() request_mocker.get( 'https://logfire-us.pydantic.dev/v1/info', json={'project_name': 'myproject', 'project_url': 'fake_project_url'}, ) with request_mocker: logfire.configure( send_to_logfire=True, token='abc1', console=False, ) wait_for_check_token_thread() dynamic_batch_span_processor, *_ = get_span_processors() assert isinstance(dynamic_batch_span_processor, DynamicBatchSpanProcessor) batch_processor = dynamic_batch_span_processor.batch_processor ex = batch_processor.span_exporter = batch_processor._exporter = TrackingExporter() # type: ignore return ex def check_delays(exp: TrackingExporter, min_delay: float, max_delay: float) -> None: for delay in exp.export_delays: assert min_delay < delay < max_delay, f'delay was {delay}, which is not between {min_delay} and {max_delay}' # test the default behaviour exporter = configure_tracking_exporter() for _ in range(10): logfire.info('test') sleep(0.1) # Initially the delay is 100 ms check_delays(exporter, 0.1, 0.4) exporter.export_delays.clear() while not exporter.export_delays: with logfire.span('test'): pass sleep(0.1) # After the first 10 spans, we increase to 500ms by default check_delays(exporter, 0.4, 1.0) # test a very small value with patch.dict(os.environ, {'OTEL_BSP_SCHEDULE_DELAY': '1'}): exporter = configure_tracking_exporter() while not exporter.export_delays: with logfire.span('test'): pass sleep(0.03) check_delays(exporter, 0.0, 0.1) # since we set 1ms it should be a very short delay def test_configure_service_version(config_kwargs: dict[str, Any], exporter: TestExporter, tmp_path: str) -> None: import subprocess git_sha = subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode('ascii').strip() def resource_service_version() -> str | None: logfire.info('test') [span] = exporter.exported_spans_as_dict(include_resources=True) exporter.clear() return span['resource']['attributes'].get('service.version') # Explicit version: stored on the config and used in the resource. configure(service_version='1.2.3', **config_kwargs) assert GLOBAL_CONFIG.service_version == '1.2.3' assert resource_service_version() == '1.2.3' # No explicit version: the git commit hash is used in the resource as a low-precedence fallback (so # `OTEL_RESOURCE_ATTRIBUTES` can still override it here), and is stored back on the config so it's reflected # in the configuration span and serialized to child processes. configure(**config_kwargs) assert GLOBAL_CONFIG.service_version == git_sha assert resource_service_version() == git_sha # No git available: no `service.version` at all. dir = os.getcwd() try: os.chdir(tmp_path) configure(**config_kwargs) assert GLOBAL_CONFIG.service_version is None assert resource_service_version() is None finally: os.chdir(dir) def test_otel_service_name_env_var(config_kwargs: dict[str, Any], exporter: TestExporter) -> None: with patch.dict(os.environ, {'OTEL_SERVICE_NAME': 'potato'}): configure(service_version='1.2.3', **config_kwargs) logfire.info('test1') assert exporter.exported_spans_as_dict(include_resources=True) == snapshot( [ { 'name': 'test1', 'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'parent': None, 'start_time': 1000000000, 'end_time': 1000000000, 'attributes': { 'logfire.span_type': 'log', 'logfire.level_num': 9, 'logfire.msg_template': 'test1', 'logfire.msg': 'test1', 'code.filepath': 'test_configure.py', 'code.function': 'test_otel_service_name_env_var', 'code.lineno': 123, }, 'resource': { 'attributes': { 'telemetry.sdk.language': 'python', 'telemetry.sdk.name': 'opentelemetry', 'telemetry.sdk.version': '0.0.0', 'service.name': 'potato', 'service.version': '1.2.3', 'logfire.version': VERSION, 'service.instance.id': '00000000000000000000000000000000', 'process.runtime.name': 'cpython', 'process.runtime.version': IsStr(regex=PROCESS_RUNTIME_VERSION_REGEX), 'process.runtime.description': sys.version, 'host.name': IsStr(), 'host.arch': IsStr(), 'os.type': IsStr(), 'os.version': IsStr(), 'process.pid': 1234, } }, } ] ) def test_otel_otel_resource_attributes_env_var(config_kwargs: dict[str, Any], exporter: TestExporter) -> None: with patch.dict( os.environ, {'OTEL_RESOURCE_ATTRIBUTES': 'service.name=banana,service.version=1.2.3,service.instance.id=instance_id'}, ): configure(**config_kwargs) logfire.info('test1') assert exporter.exported_spans_as_dict(include_resources=True) == snapshot( [ { 'name': 'test1', 'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'parent': None, 'start_time': 1000000000, 'end_time': 1000000000, 'attributes': { 'logfire.span_type': 'log', 'logfire.level_num': 9, 'logfire.msg_template': 'test1', 'logfire.msg': 'test1', 'code.filepath': 'test_configure.py', 'code.function': 'test_otel_otel_resource_attributes_env_var', 'code.lineno': 123, }, 'resource': { 'attributes': { 'telemetry.sdk.language': 'python', 'telemetry.sdk.name': 'opentelemetry', 'telemetry.sdk.version': '0.0.0', 'service.name': 'banana', 'service.version': '1.2.3', 'service.instance.id': 'instance_id', 'logfire.version': VERSION, 'process.pid': 1234, 'process.runtime.name': 'cpython', 'process.runtime.version': IsStr(regex=PROCESS_RUNTIME_VERSION_REGEX), 'process.runtime.description': sys.version, 'host.name': IsStr(), 'host.arch': IsStr(), 'os.type': IsStr(), 'os.version': IsStr(), } }, } ] ) def test_otel_service_name_has_priority_on_otel_resource_attributes_service_name_env_var( config_kwargs: dict[str, Any], exporter: TestExporter ) -> None: with patch.dict( os.environ, dict(OTEL_SERVICE_NAME='potato', OTEL_RESOURCE_ATTRIBUTES='service.name=banana,service.version=1.2.3'), ): configure(**config_kwargs) logfire.info('test1') assert exporter.exported_spans_as_dict(include_resources=True) == snapshot( [ { 'name': 'test1', 'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'parent': None, 'start_time': 1000000000, 'end_time': 1000000000, 'attributes': { 'logfire.span_type': 'log', 'logfire.level_num': 9, 'logfire.msg_template': 'test1', 'logfire.msg': 'test1', 'code.filepath': 'test_configure.py', 'code.function': 'test_otel_service_name_has_priority_on_otel_resource_attributes_service_name_env_var', 'code.lineno': 123, }, 'resource': { 'attributes': { 'telemetry.sdk.language': 'python', 'telemetry.sdk.name': 'opentelemetry', 'telemetry.sdk.version': '0.0.0', # `OTEL_SERVICE_NAME` takes priority over `service.name` in `OTEL_RESOURCE_ATTRIBUTES`, # matching OpenTelemetry's own semantics. 'service.name': 'potato', 'service.version': '1.2.3', 'service.instance.id': '00000000000000000000000000000000', 'logfire.version': VERSION, 'process.pid': 1234, 'process.runtime.name': 'cpython', 'process.runtime.version': IsStr(regex=PROCESS_RUNTIME_VERSION_REGEX), 'process.runtime.description': sys.version, 'host.name': IsStr(), 'host.arch': IsStr(), 'os.type': IsStr(), 'os.version': IsStr(), } }, } ] ) def test_resource_attributes_advanced_option(config_kwargs: dict[str, Any], exporter: TestExporter) -> None: config_kwargs['resource_attributes'] = {'host.name': 'my-host', 'custom.thing': 'from-kwarg'} with patch.dict(os.environ, {'OTEL_RESOURCE_ATTRIBUTES': 'custom.thing=from-env'}): configure(**config_kwargs) logfire.info('test1') [span] = exporter.exported_spans_as_dict(include_resources=True) assert span['resource']['attributes'] == IsPartialDict( { 'host.name': 'my-host', # The explicit `resource_attributes` kwarg takes precedence over the OTEL_RESOURCE_ATTRIBUTES env var. 'custom.thing': 'from-kwarg', } ) def test_dedicated_args_take_precedence_over_resource_attributes( config_kwargs: dict[str, Any], exporter: TestExporter ) -> None: # The dedicated `service_name`/`service_version`/`environment` args win over the same keys set generically # via `resource_attributes`, and each override emits a warning. config_kwargs['resource_attributes'] = { 'service.name': 'from-attrs', 'service.version': 'from-attrs', 'deployment.environment.name': 'from-attrs', 'custom.thing': 'from-attrs', } with pytest.warns(LogfireConfigWarning) as warnings: configure(**config_kwargs, service_name='from-arg', service_version='from-arg', environment='from-arg') # One warning per dedicated argument that overrode a different `resource_attributes` value; the key with no # dedicated argument (`custom.thing`) doesn't warn. messages = '\n'.join(str(w.message) for w in warnings) assert "The 'service.name' resource attribute is set both via" in messages assert "The 'service.version' resource attribute is set both via" in messages assert "The 'deployment.environment.name' resource attribute is set both via" in messages assert "'custom.thing'" not in messages logfire.info('test1') [span] = exporter.exported_spans_as_dict(include_resources=True) assert span['resource']['attributes'] == IsPartialDict( { 'service.name': 'from-arg', 'service.version': 'from-arg', 'deployment.environment.name': 'from-arg', # A key with no dedicated argument still comes from `resource_attributes`. 'custom.thing': 'from-attrs', } ) @pytest.mark.parametrize('detectors', [['*'], 'process', ['process']]) def test_resource_detectors(detectors: str | list[str], config_kwargs: dict[str, Any], exporter: TestExporter) -> None: # A list of names, a bare string (coerced to a single-element list), and `'*'` (every registered detector) # all run the `process` detector, which adds attributes that aren't pre-populated by default. config_kwargs['advanced'] = dataclasses.replace(config_kwargs['advanced'], resource_detectors=detectors) configure(**config_kwargs) logfire.info('test1') [span] = exporter.exported_spans_as_dict(include_resources=True) # The `process` detector adds attributes that aren't pre-populated by default. assert span['resource']['attributes'] == IsPartialDict( { 'process.owner': getpass.getuser(), 'process.executable.name': IsStr(), 'process.executable.path': IsStr(), } ) def test_resource_detector_instance(config_kwargs: dict[str, Any], exporter: TestExporter) -> None: class MyDetector(ResourceDetector): def detect(self) -> Resource: return Resource({'custom.thing': 'detected', 'service.version': 'detected-version'}) config_kwargs['advanced'] = dataclasses.replace(config_kwargs['advanced'], resource_detectors=[MyDetector()]) configure(**config_kwargs, service_version='explicit-version') logfire.info('test1') [span] = exporter.exported_spans_as_dict(include_resources=True) assert span['resource']['attributes'] == IsPartialDict( { 'custom.thing': 'detected', # Explicitly set attributes take precedence over detectors. 'service.version': 'explicit-version', } ) def test_resource_detector_unknown_name(config_kwargs: dict[str, Any], exporter: TestExporter) -> None: # An unknown detector name warns and is skipped rather than raising, so a typo can't crash the app. config_kwargs['advanced'] = dataclasses.replace( config_kwargs['advanced'], resource_detectors=['nonexistent-detector', 'process'] ) with pytest.warns(LogfireConfigWarning, match="Skipping unknown resource detector 'nonexistent-detector'"): configure(**config_kwargs) logfire.info('test1') # The valid detector alongside the unknown one is still applied. [span] = exporter.exported_spans_as_dict(include_resources=True) assert span['resource']['attributes'] == IsPartialDict({'process.owner': getpass.getuser()}) def test_resource_detector_load_failure(config_kwargs: dict[str, Any], exporter: TestExporter) -> None: # A registered detector that raises while loading warns and is skipped rather than crashing the app. class FailingEntryPoint: name = 'failing' def load(self): def make_detector(): raise RuntimeError('boom') return make_detector config_kwargs['advanced'] = dataclasses.replace(config_kwargs['advanced'], resource_detectors=['failing']) with patch('logfire._internal.config.entry_points', return_value=[FailingEntryPoint()]): with pytest.warns(LogfireConfigWarning, match="Failed to load resource detector 'failing': boom"): configure(**config_kwargs) logfire.info('test1') # Configuration still succeeds with the default resource attributes despite the failing detector. [span] = exporter.exported_spans_as_dict(include_resources=True) assert span['resource']['attributes'] == IsPartialDict({'process.runtime.name': IsStr()}) def test_resource_detector_unknown_name_in_env_var(config_kwargs: dict[str, Any]) -> None: # The env var follows the same tolerant semantics as OTEL_EXPERIMENTAL_RESOURCE_DETECTORS. with patch.dict(os.environ, {'LOGFIRE_RESOURCE_DETECTORS': 'nonexistent-detector'}): with pytest.warns(LogfireConfigWarning, match="Skipping unknown resource detector 'nonexistent-detector'"): configure(**config_kwargs) def test_resource_detectors_take_precedence_over_env_var_detectors( config_kwargs: dict[str, Any], exporter: TestExporter ) -> None: class CommandDetector(ResourceDetector): def detect(self) -> Resource: return Resource({'process.command': 'from-kwarg-detector'}) config_kwargs['advanced'] = dataclasses.replace(config_kwargs['advanced'], resource_detectors=[CommandDetector()]) with patch.dict(os.environ, {'OTEL_EXPERIMENTAL_RESOURCE_DETECTORS': 'process'}): configure(**config_kwargs) logfire.info('test1') [span] = exporter.exported_spans_as_dict(include_resources=True) attributes = span['resource']['attributes'] # `resource_detectors` takes precedence over `OTEL_EXPERIMENTAL_RESOURCE_DETECTORS`. assert attributes['process.command'] == 'from-kwarg-detector' # The env var detector still contributes attributes that the kwarg detector doesn't override. assert attributes['process.owner'] == getpass.getuser() def test_resource_attributes_env_var(config_kwargs: dict[str, Any], exporter: TestExporter) -> None: with patch.dict( os.environ, { # The `malformed` item has no `=` and is silently skipped. 'LOGFIRE_RESOURCE_ATTRIBUTES': 'custom.thing=from-logfire-env,other=value,malformed', 'OTEL_RESOURCE_ATTRIBUTES': 'custom.thing=from-otel-env', }, ): configure(**config_kwargs) logfire.info('test1') [span] = exporter.exported_spans_as_dict(include_resources=True) attributes = span['resource']['attributes'] assert attributes['other'] == 'value' assert 'malformed' not in attributes # LOGFIRE_RESOURCE_ATTRIBUTES (a `logfire.configure()` source) takes precedence over OTEL_RESOURCE_ATTRIBUTES. assert attributes['custom.thing'] == 'from-logfire-env' def test_resource_detectors_env_var(config_kwargs: dict[str, Any], exporter: TestExporter) -> None: with patch.dict(os.environ, {'LOGFIRE_RESOURCE_DETECTORS': 'process'}): configure(**config_kwargs) logfire.info('test1') [span] = exporter.exported_spans_as_dict(include_resources=True) assert span['resource']['attributes'] == IsPartialDict({'process.owner': getpass.getuser()}) def test_resource_attributes_and_detectors_from_pyproject_toml( config_kwargs: dict[str, Any], exporter: TestExporter, tmp_path: Path ) -> None: (tmp_path / 'pyproject.toml').write_text( """ [tool.logfire] resource_attributes = {"custom.thing" = "from-file"} resource_detectors = ["process"] """ ) configure(**config_kwargs, config_dir=tmp_path) logfire.info('test1') [span] = exporter.exported_spans_as_dict(include_resources=True) attributes = span['resource']['attributes'] assert attributes['custom.thing'] == 'from-file' assert attributes['process.owner'] == getpass.getuser() def test_explicit_service_version_takes_precedence_over_otel_resource_attributes( config_kwargs: dict[str, Any], exporter: TestExporter ) -> None: # An explicit `service_version` beats OTEL_RESOURCE_ATTRIBUTES; the git-hash fallback does not # (see `test_otel_otel_resource_attributes_env_var`). with patch.dict(os.environ, {'OTEL_RESOURCE_ATTRIBUTES': 'service.version=from-env'}): configure(**config_kwargs, service_version='explicit-version') logfire.info('test1') [span] = exporter.exported_spans_as_dict(include_resources=True) assert span['resource']['attributes']['service.version'] == 'explicit-version' def test_auto_detected_service_version_serialized() -> None: """An auto-detected (git) `service_version` is stored back on the config when the resource is built, so it's reflected in the configuration span and serialized to child processes (which then treat it as an explicit value). An explicitly-passed `service_version` is stored and serialized as-is. """ import subprocess git_sha = subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode('ascii').strip() # In the logfire repo, the version is auto-detected from git and stored on the config. configure(send_to_logfire=False, console=False) assert GLOBAL_CONFIG.service_version == git_sha serialized = serialize_config() assert serialized is not None assert serialized['service_version'] == git_sha # An explicit version is stored and preserved across serialization. configure(send_to_logfire=False, console=False, service_version='explicit-version') assert GLOBAL_CONFIG.service_version == 'explicit-version' serialized = serialize_config() assert serialized is not None assert serialized['service_version'] == 'explicit-version' def test_host_and_os_resource_attributes_populated_by_default( config_kwargs: dict[str, Any], exporter: TestExporter ) -> None: """`host.*` and `os.*` are pre-populated with the same values OTel's `_HostResourceDetector` and `OsResourceDetector` would emit, so the Hosts page works without the customer enabling the experimental detector env var. """ import platform import socket # Hermetic: an inherited `OTEL_RESOURCE_ATTRIBUTES` from the runner shell # would override our defaults and make this test pass spuriously. with patch.dict(os.environ, {}, clear=False): os.environ.pop('OTEL_RESOURCE_ATTRIBUTES', None) configure(**config_kwargs) logfire.info('test') resource_attrs = exporter.exported_spans_as_dict(include_resources=True)[0]['resource']['attributes'] assert resource_attrs['host.name'] == socket.gethostname() assert resource_attrs['host.arch'] == platform.machine() assert resource_attrs['os.type'] == platform.system().lower() assert resource_attrs['os.version'] == ( platform.version() if platform.system().lower() in ('windows', 'sunos') else platform.release() ) @pytest.mark.skipif(not hasattr(os, 'register_at_fork'), reason='os.register_at_fork is not available') def test_register_at_fork_resource_updates( monkeypatch: pytest.MonkeyPatch, exporter: TestExporter, logs_exporter: TestLogExporter, metrics_reader: InMemoryMetricReader, ) -> None: callbacks: list[Callable[[], None]] = [] def register_at_fork(*, after_in_child: Callable[[], None]) -> None: callbacks.append(after_in_child) monkeypatch.setattr(config_module.os, 'register_at_fork', register_at_fork) monkeypatch.setattr(config_module.os, 'getpid', lambda: 42) proxy_tracer_provider = GLOBAL_CONFIG.get_tracer_provider() proxy_meter_provider = GLOBAL_CONFIG.get_meter_provider() proxy_logger_provider = GLOBAL_CONFIG.get_logger_provider() tracer_provider = proxy_tracer_provider.provider meter_provider = proxy_meter_provider.provider logger_provider = proxy_logger_provider.provider assert isinstance(tracer_provider, config_module.SDKTracerProvider) assert isinstance(meter_provider, config_module.MeterProvider) assert isinstance(logger_provider, config_module.SDKLoggerProvider) counter = logfire.metric_counter('fork.callback.counter') counter.add(1) logger = get_logger('fork.callback.logger') logger.emit(LogRecord(body='before callback')) with logfire.span('before callback'): pass metrics_reader.get_metrics_data() exporter.clear() logs_exporter.clear() config_module._register_at_fork_resource_updates( # pyright: ignore[reportPrivateUsage] proxy_tracer_provider, proxy_meter_provider, proxy_logger_provider, ) [callback] = callbacks callback() counter.add(1) logger.emit(LogRecord(body='after callback')) with logfire.span('after callback'): pass metrics_data = metrics_reader.get_metrics_data() assert metrics_data is not None assert metrics_data.resource_metrics[0].resource.attributes['process.pid'] == 42 assert exporter.exported_spans[-1].resource.attributes['process.pid'] == 42 assert logs_exporter.get_finished_logs()[-1].resource.attributes['process.pid'] == 42 suppressed_scope = 'fork.callback.suppressed' proxy_tracer_provider.suppress_scopes(suppressed_scope) proxy_logger_provider.suppress_scopes(suppressed_scope) suppressed_tracer = proxy_tracer_provider.get_tracer(suppressed_scope) suppressed_logger = proxy_logger_provider.get_logger(suppressed_scope) callbacks.clear() noop_proxy_meter_provider = config_module.ProxyMeterProvider(NoOpMeterProvider()) config_module._register_at_fork_resource_updates( # pyright: ignore[reportPrivateUsage] proxy_tracer_provider, noop_proxy_meter_provider, proxy_logger_provider, ) [callback] = callbacks callback() assert suppressed_tracer.instrumenting_module_name == suppressed_scope assert suppressed_logger callbacks.clear() noop_proxy_tracer_provider = config_module.ProxyTracerProvider( config_module.trace.NoOpTracerProvider(), GLOBAL_CONFIG ) noop_proxy_logger_provider = config_module.ProxyLoggerProvider(config_module.NoOpLoggerProvider()) config_module._register_at_fork_resource_updates( # pyright: ignore[reportPrivateUsage] noop_proxy_tracer_provider, noop_proxy_meter_provider, noop_proxy_logger_provider, ) [callback] = callbacks callback() callbacks.clear() config_module._register_at_fork_resource_updates( # pyright: ignore[reportPrivateUsage] config_module.ProxyTracerProvider(config_module.trace.NoOpTracerProvider(), GLOBAL_CONFIG), config_module.ProxyMeterProvider(NoOpMeterProvider()), config_module.ProxyLoggerProvider(config_module.NoOpLoggerProvider()), ) [callback] = callbacks callback() def test_otel_resource_updater_sources() -> None: provider_classes = { 'traces': config_module.SDKTracerProvider, 'metrics': config_module.MeterProvider, 'logs': config_module.SDKLoggerProvider, } if not all(hasattr(provider_class, '_update_resource') for provider_class in provider_classes.values()): pytest.skip('OpenTelemetry resource updaters were added in version 1.44') # The fork callback manually performs the lock-free equivalent of these private methods. Fail loudly if an # OpenTelemetry upgrade changes the state that needs updating. assert { name: inspect.getsource(getattr(provider_class, '_update_resource')) for name, provider_class in provider_classes.items() } == snapshot( { 'traces': """\ def _update_resource(self, resource: Resource) -> None: with self._tracers_lock: self._resource = self._resource.merge(resource) for tracer in self._tracers.values(): tracer._set_resource(self._resource) # pylint: disable=protected-access """, 'metrics': """\ def _update_resource(self, resource: Resource) -> None: with self._meter_lock: self._sdk_config.resource = self._sdk_config.resource.merge( resource ) """, 'logs': """\ def _update_resource(self, resource: Resource) -> None: with self._active_loggers_lock: self._resource = self._resource.merge(resource) for logger in list(self._active_loggers): # pylint: disable-next=protected-access logger._set_resource(self._resource) """, } ) @pytest.mark.skipif(not hasattr(os, 'fork'), reason='os.fork is not available') def test_resource_process_pid_updated_after_fork( exporter: TestExporter, logs_exporter: TestLogExporter, metrics_reader: InMemoryMetricReader ) -> None: tracer_provider = GLOBAL_CONFIG.get_tracer_provider().provider meter_provider = GLOBAL_CONFIG.get_meter_provider().provider logger_provider = GLOBAL_CONFIG.get_logger_provider().provider assert isinstance(tracer_provider, config_module.SDKTracerProvider) assert isinstance(meter_provider, config_module.MeterProvider) assert isinstance(logger_provider, config_module.SDKLoggerProvider) counter = logfire.metric_counter('fork.counter') counter.add(1) logger = get_logger('fork.logger') logger.emit(LogRecord(body='parent')) with logfire.span('parent'): pass metrics_data = metrics_reader.get_metrics_data() assert metrics_data is not None assert metrics_data.resource_metrics[0].resource.attributes['process.pid'] == os.getpid() assert exporter.exported_spans[-1].resource.attributes['process.pid'] == os.getpid() assert logs_exporter.get_finished_logs()[-1].resource.attributes['process.pid'] == os.getpid() exporter.clear() logs_exporter.clear() read_fd, write_fd = os.pipe() provider_locks = [] if all( hasattr(provider, '_handle_fork') and hasattr(provider, '_update_resource') for provider in (tracer_provider, meter_provider, logger_provider) ): provider_locks = [ tracer_provider._tracers_lock, # pyright: ignore[reportPrivateUsage] meter_provider._meter_lock, # pyright: ignore[reportPrivateUsage] logger_provider._active_loggers_lock, # pyright: ignore[reportPrivateUsage] ] for lock in provider_locks: lock.acquire() signal.alarm(10) try: with warnings.catch_warnings(): warnings.filterwarnings('ignore', category=DeprecationWarning, message='.*fork.*') child_pid = os.fork() except BaseException: signal.alarm(0) for lock in provider_locks: lock.release() raise if child_pid == 0: # pragma: no cover os.close(read_fd) try: counter.add(1) logger.emit(LogRecord(body='child')) with logfire.span('child'): pass metrics_data = metrics_reader.get_metrics_data() assert metrics_data is not None result = json.dumps( { 'metric': metrics_data.resource_metrics[0].resource.attributes['process.pid'], 'span': exporter.exported_spans[-1].resource.attributes['process.pid'], 'log': logs_exporter.get_finished_logs()[-1].resource.attributes['process.pid'], } ) exit_code = 0 except BaseException as error: result = repr(error) exit_code = 1 os.write(write_fd, result.encode()) os.close(write_fd) signal.alarm(0) os._exit(exit_code) for lock in provider_locks: lock.release() os.close(write_fd) def raise_fork_timeout(*_: object) -> None: raise TimeoutError('forked child process timed out') previous_alarm_handler = signal.signal(signal.SIGALRM, raise_fork_timeout) signal.alarm(10) try: with os.fdopen(read_fd) as read_file: result = read_file.read() _, status = os.waitpid(child_pid, 0) finally: signal.alarm(0) signal.signal(signal.SIGALRM, previous_alarm_handler) assert os.waitstatus_to_exitcode(status) == 0, result assert json.loads(result) == {'metric': child_pid, 'span': child_pid, 'log': child_pid} def test_otel_resource_attributes_env_var_overrides_host_and_os_defaults( config_kwargs: dict[str, Any], exporter: TestExporter ) -> None: """`OTEL_RESOURCE_ATTRIBUTES` wins over the pre-populated `host.*` / `os.*` so customers whose `socket.gethostname()` is useless (e.g. random container IDs) can override cleanly. """ with patch.dict( os.environ, {'OTEL_RESOURCE_ATTRIBUTES': 'host.name=my-explicit-host,host.arch=my-arch,os.type=plan9,os.version=4'}, ): configure(**config_kwargs) logfire.info('test') resource_attrs = exporter.exported_spans_as_dict(include_resources=True)[0]['resource']['attributes'] assert resource_attrs['host.name'] == 'my-explicit-host' assert resource_attrs['host.arch'] == 'my-arch' assert resource_attrs['os.type'] == 'plan9' assert resource_attrs['os.version'] == '4' def test_config_serializable(): """ Tests that by default, the logfire config can be serialized in the way that we do when sending it to another process. Here's an example of a configuration that (as of writing) fails to serialize: from opentelemetry.sdk.trace.export import SimpleSpanProcessor import logfire from logfire._internal.exporters.console import SimpleConsoleSpanExporter from logfire._internal.integrations.executors import serialize_config logfire.configure(additional_span_processors=[SimpleSpanProcessor(SimpleConsoleSpanExporter())]) serialize_config() # fails because SimpleConsoleSpanExporter contains sys.stdout This implies that the default processors cannot be stored in the config alongside user-defined processors. In particular we also need to check that config values that are dataclasses are handled properly: they get serialized to dicts (which dataclasses.asdict does automatically), and deserialized back to dataclasses (which we have to do manually). """ # Mock the remote variables endpoint to prevent real network requests with requests_mock.Mocker() as m: m.get(requests_mock.ANY, json={'variables': {}, 'aliases': None}) logfire.configure( send_to_logfire=False, console=logfire.ConsoleOptions(verbose=True), sampling=logfire.SamplingOptions(), scrubbing=logfire.ScrubbingOptions(), code_source=logfire.CodeSource(repository='https://github.com/pydantic/logfire', revision='main'), api_key='test_api_key', variables=VariablesOptions( block_before_first_resolve=False, include_baggage_in_context=False, ), advanced=logfire.AdvancedOptions(id_generator=SeededRandomIdGenerator(seed=42)), ) for field in dataclasses.fields(GLOBAL_CONFIG): # Check that the full set of dataclass fields is known. # If a new field appears here, make sure it gets deserialized properly in configure, and tested here. assert dataclasses.is_dataclass(getattr(GLOBAL_CONFIG, field.name)) == ( field.name in ['console', 'sampling', 'scrubbing', 'advanced', 'code_source', 'variables'] ) serialized = serialize_config() assert serialized is not None # Config should be picklable in this test GLOBAL_CONFIG._initialized = False # type: ignore # ensure deserialize_config actually configures deserialize_config(pickle.loads(pickle.dumps(serialized))) serialized2 = pickle.loads(pickle.dumps(serialize_config())) assert serialized2 is not None # Config should be picklable in this test def normalize(s: dict[str, Any]) -> dict[str, Any]: for value in s.values(): assert not dataclasses.is_dataclass(value) return s assert normalize(serialized) == normalize(serialized2) assert isinstance(GLOBAL_CONFIG.console, logfire.ConsoleOptions) assert isinstance(GLOBAL_CONFIG.sampling, logfire.SamplingOptions) assert isinstance(GLOBAL_CONFIG.scrubbing, logfire.ScrubbingOptions) assert isinstance(GLOBAL_CONFIG.advanced, logfire.AdvancedOptions) assert isinstance(GLOBAL_CONFIG.advanced.id_generator, SeededRandomIdGenerator) assert isinstance(GLOBAL_CONFIG.variables, logfire.VariablesOptions) assert GLOBAL_CONFIG.advanced.id_generator.seed == 42 # Clean up the remote variable provider to stop the background thread logfire.configure(send_to_logfire=False) def test_config_serializable_console_false(): logfire.configure(send_to_logfire=False, console=False) assert GLOBAL_CONFIG.console is False deserialize_config(serialize_config()) assert GLOBAL_CONFIG.console is False def test_serialize_config_unpicklable(): """Test serialize_config when config cannot be pickled.""" from logfire._internal.tracer import record_exception from logfire.types import ExceptionCallbackHelper def local_exception_callback(helper: ExceptionCallbackHelper) -> None: pass logfire.configure( send_to_logfire=False, advanced=logfire.AdvancedOptions(exception_callback=local_exception_callback), additional_span_processors=[BatchSpanProcessor(SimpleConsoleSpanExporter())], ) # Call the callback to cover the pass statement with logfire.span('test') as span: try: raise ValueError('test') except ValueError as e: record_exception(span._span, e, callback=GLOBAL_CONFIG.advanced.exception_callback) # type: ignore with pytest.warns(UserWarning, match='cannot be pickled'): result = serialize_config() assert result is None deserialize_config(None) def test_config_console_output_set(): output = StringIO() logfire.configure(send_to_logfire=False, console=logfire.ConsoleOptions(output=output)) assert isinstance(GLOBAL_CONFIG.console, logfire.ConsoleOptions) assert GLOBAL_CONFIG.console.output is output deserialize_config(serialize_config()) assert isinstance(GLOBAL_CONFIG.console, logfire.ConsoleOptions) assert GLOBAL_CONFIG.console.output is output logfire.info('test') assert 'test' in output.getvalue() def test_sanitize_project_name(): assert sanitize_project_name('foo') == 'foo' assert sanitize_project_name('FOO') == 'foo' assert sanitize_project_name(' foo - bar!!') == 'foobar' assert sanitize_project_name(' Foo - BAR!!') == 'foobar' assert sanitize_project_name('') == 'untitled' assert sanitize_project_name('-') == 'untitled' assert sanitize_project_name('...') == 'untitled' long_name = 'abcdefg' * 20 assert sanitize_project_name(long_name) == long_name[:41] def test_initialize_project_use_existing_project_no_projects(tmp_dir_cwd: Path, tmp_path: Path): auth_file = tmp_path / 'default.toml' auth_file.write_text( '[tokens."https://logfire-api.pydantic.dev"]\ntoken = "fake_user_token"\nexpiration = "2099-12-31T23:59:59"' ) with ExitStack() as stack: stack.enter_context(mock.patch('logfire._internal.auth.DEFAULT_FILE', auth_file)) confirm_mock = stack.enter_context(mock.patch('rich.prompt.Confirm.ask', side_effect=[True, True])) stack.enter_context(mock.patch('rich.prompt.Prompt.ask', side_effect=['', 'myproject', ''])) request_mocker = requests_mock.Mocker() stack.enter_context(request_mocker) request_mocker.get('https://logfire-api.pydantic.dev/v1/writable-projects/', json=[]) request_mocker.get( 'https://logfire-api.pydantic.dev/v1/organizations/available-for-projects/', json=[{'organization_name': 'fake_org'}], ) request_mocker.get( 'https://logfire-api.pydantic.dev/v1/info', json={'project_name': 'myproject', 'project_url': 'fake_project_url'}, ) create_project_response = { 'json': { 'project_name': 'myproject', 'token': 'fake_token', 'project_url': 'fake_project_url', } } request_mocker.post( 'https://logfire-api.pydantic.dev/v1/organizations/fake_org/projects', [create_project_response] ) logfire.configure(send_to_logfire=True) wait_for_check_token_thread() assert confirm_mock.mock_calls == [ call('The project will be created in the organization "fake_org". Continue?', default=True), ] def test_initialize_project_use_existing_project(tmp_dir_cwd: Path, tmp_path: Path, capsys: pytest.CaptureFixture[str]): auth_file = tmp_path / 'default.toml' auth_file.write_text( '[tokens."https://logfire-api.pydantic.dev"]\ntoken = "fake_user_token"\nexpiration = "2099-12-31T23:59:59"' ) with ExitStack() as stack: stack.enter_context(mock.patch('logfire._internal.auth.DEFAULT_FILE', auth_file)) confirm_mock = stack.enter_context(mock.patch('rich.prompt.Confirm.ask', side_effect=[True, True])) prompt_mock = stack.enter_context(mock.patch('rich.prompt.Prompt.ask', side_effect=['1', ''])) request_mocker = requests_mock.Mocker() stack.enter_context(request_mocker) request_mocker.get( 'https://logfire-api.pydantic.dev/v1/writable-projects/', json=[{'organization_name': 'fake_org', 'project_name': 'fake_project'}], ) request_mocker.get( 'https://logfire-api.pydantic.dev/v1/info', json={'project_name': 'myproject', 'project_url': 'fake_project_url'}, ) create_project_response = { 'json': { 'project_name': 'myproject', 'token': 'fake_token', 'project_url': 'fake_project_url', } } request_mocker.post( 'https://logfire-api.pydantic.dev/v1/organizations/fake_org/projects/fake_project/write-tokens/', [create_project_response], ) logfire.configure(send_to_logfire=True) assert confirm_mock.mock_calls == [ call('Do you want to use one of your existing projects? ', default=True), ] assert prompt_mock.mock_calls == [ call( "Please select one of the following projects by number (requires the 'write_token' permission):\n1. fake_org/fake_project\n", choices=['1'], default='1', ), call( 'Project initialized successfully. You will be able to view it at: fake_project_url\nPress Enter to continue', ), ] wait_for_check_token_thread() assert capsys.readouterr().err == 'Logfire project URL: fake_project_url\n' assert json.loads((tmp_dir_cwd / '.logfire/logfire_credentials.json').read_text()) == { **create_project_response['json'], 'logfire_api_url': 'https://logfire-api.pydantic.dev', } def test_initialize_project_not_using_existing_project( tmp_dir_cwd: Path, tmp_path: Path, capsys: pytest.CaptureFixture[str] ): auth_file = tmp_path / 'default.toml' auth_file.write_text( '[tokens."https://logfire-api.pydantic.dev"]\ntoken = "fake_user_token"\nexpiration = "2099-12-31T23:59:59"' ) with ExitStack() as stack: stack.enter_context(mock.patch('logfire._internal.auth.DEFAULT_FILE', auth_file)) confirm_mock = stack.enter_context(mock.patch('rich.prompt.Confirm.ask', side_effect=[False, True])) prompt_mock = stack.enter_context(mock.patch('rich.prompt.Prompt.ask', side_effect=['my-project', ''])) request_mocker = requests_mock.Mocker() stack.enter_context(request_mocker) request_mocker.get( 'https://logfire-api.pydantic.dev/v1/organizations/available-for-projects/', json=[{'organization_name': 'fake_org'}], ) request_mocker.get( 'https://logfire-api.pydantic.dev/v1/info', json={'project_name': 'myproject', 'project_url': 'fake_project_url'}, ) request_mocker.get( 'https://logfire-api.pydantic.dev/v1/writable-projects/', json=[{'organization_name': 'fake_org', 'project_name': 'fake_project'}], ) create_project_response = { 'json': { 'project_name': 'myproject', 'token': 'fake_token', 'project_url': 'fake_project_url', } } request_mocker.post( 'https://logfire-api.pydantic.dev/v1/organizations/fake_org/projects', [create_project_response] ) request_mocker.post( 'https://logfire-api.pydantic.dev/v1/organizations/fake_org/projects/fake_project/write-tokens/', [create_project_response], ) logfire.configure(send_to_logfire=True) assert confirm_mock.mock_calls == [ call('Do you want to use one of your existing projects? ', default=True), call('The project will be created in the organization "fake_org". Continue?', default=True), ] assert prompt_mock.mock_calls == [ call('Enter the project name', default='testinitializeprojectnotus0'), call( 'Project initialized successfully. You will be able to view it at: fake_project_url\nPress Enter to continue' ), ] wait_for_check_token_thread() assert capsys.readouterr().err == 'Logfire project URL: fake_project_url\n' assert json.loads((tmp_dir_cwd / '.logfire/logfire_credentials.json').read_text()) == { **create_project_response['json'], 'logfire_api_url': 'https://logfire-api.pydantic.dev', } def test_initialize_project_not_confirming_organization(tmp_path: Path) -> None: auth_file = tmp_path / 'default.toml' auth_file.write_text( '[tokens."https://logfire-api.pydantic.dev"]\ntoken = "fake_user_token"\nexpiration = "2099-12-31T23:59:59"' ) with ExitStack() as stack: stack.enter_context(mock.patch('logfire._internal.auth.DEFAULT_FILE', auth_file)) confirm_mock = stack.enter_context(mock.patch('rich.prompt.Confirm.ask', side_effect=[False, False])) request_mocker = requests_mock.Mocker() stack.enter_context(request_mocker) request_mocker.get( 'https://logfire-api.pydantic.dev/v1/organizations/available-for-projects/', json=[{'organization_name': 'fake_org'}], ) request_mocker.get( 'https://logfire-api.pydantic.dev/v1/writable-projects/', json=[{'organization_name': 'fake_org', 'project_name': 'fake_project'}], ) with pytest.raises(SystemExit): logfire.configure(data_dir=tmp_path, send_to_logfire=True) wait_for_check_token_thread() assert confirm_mock.mock_calls == [ call('Do you want to use one of your existing projects? ', default=True), call('The project will be created in the organization "fake_org". Continue?', default=True), ] @pytest.mark.xdist_group(name='sequential') def test_initialize_project_create_project(tmp_dir_cwd: Path, tmp_path: Path, capsys: pytest.CaptureFixture[str]): auth_file = tmp_path / 'default.toml' auth_file.write_text( '[tokens."https://logfire-api.pydantic.dev"]\ntoken = "fake_user_token"\nexpiration = "2099-12-31T23:59:59"' ) with ExitStack() as stack: stack.enter_context(mock.patch('logfire._internal.auth.DEFAULT_FILE', auth_file)) confirm_mock = stack.enter_context(mock.patch('rich.prompt.Confirm.ask', side_effect=[True, True])) prompt_mock = stack.enter_context( mock.patch( 'rich.prompt.Prompt.ask', side_effect=[ 'invalid project name', 'existingprojectname', 'reserved', 'myproject', '', ], ) ) request_mocker = requests_mock.Mocker() stack.enter_context(request_mocker) request_mocker.get('https://logfire-api.pydantic.dev/v1/writable-projects/', json=[]) request_mocker.get( 'https://logfire-api.pydantic.dev/v1/organizations/available-for-projects/', json=[{'organization_name': 'fake_org'}], ) request_mocker.get( 'https://logfire-api.pydantic.dev/v1/info', json={'project_name': 'myproject', 'project_url': 'fake_project_url'}, ) create_existing_project_request_json = { 'project_name': 'existingprojectname', } create_existing_project_response = { 'status_code': 409, } create_reserved_project_request_json = { 'project_name': 'reserved', } create_reserved_project_response = { 'status_code': 422, 'json': { 'detail': [ { 'loc': ['body', 'project_name'], 'msg': 'This project name is reserved and cannot be used.', } ], }, } create_project_request_json = { 'project_name': 'myproject', } create_project_response = { 'json': { 'project_name': 'myproject', 'token': 'fake_token', 'project_url': 'fake_project_url', } } request_mocker.post( 'https://logfire-api.pydantic.dev/v1/organizations/fake_org/projects', [ create_existing_project_response, create_reserved_project_response, create_project_response, ], ) logfire.configure(send_to_logfire=True) assert capsys.readouterr().err == 'Logfire project URL: fake_project_url\n' for request in request_mocker.request_history[:5]: assert request.headers['Authorization'] == 'fake_user_token' assert len(request_mocker.request_history) in (5, 6) # we check that fake_token is valid now when we configure the project wait_for_check_token_thread() assert len(request_mocker.request_history) == 6 assert request_mocker.request_history[-1].headers['Authorization'] == 'fake_token' assert request_mocker.request_history[2].json() == create_existing_project_request_json assert request_mocker.request_history[3].json() == create_reserved_project_request_json assert request_mocker.request_history[4].json() == create_project_request_json assert confirm_mock.mock_calls == [ call('The project will be created in the organization "fake_org". Continue?', default=True), ] assert prompt_mock.mock_calls == [ call( 'Enter the project name', default='testinitializeprojectcreate0', ), call( "\nThe project name you've entered is invalid. Valid project names:\n" ' * may contain lowercase alphanumeric characters\n' ' * may contain single hyphens\n' ' * may not start or end with a hyphen\n\n' 'Enter the project name you want to use:', default='testinitializeprojectcreate0', ), call( "\nA project with the name 'existingprojectname' already exists. Please enter a different project name", default=..., ), call( '\nThe project name you entered is invalid:\n' 'This project name is reserved and cannot be used.\n' 'Please enter a different project name', default=..., ), call( 'Project initialized successfully. You will be able to view it at: fake_project_url\nPress Enter to continue', ), ] assert json.loads((tmp_dir_cwd / '.logfire/logfire_credentials.json').read_text()) == { **create_project_response['json'], 'logfire_api_url': 'https://logfire-api.pydantic.dev', } @pytest.mark.xdist_group(name='sequential') def test_initialize_project_create_project_default_organization(tmp_dir_cwd: Path, tmp_path: Path): auth_file = tmp_path / 'default.toml' auth_file.write_text( '[tokens."https://logfire-api.pydantic.dev"]\ntoken = "fake_user_token"\nexpiration = "2099-12-31T23:59:59"' ) with ExitStack() as stack: stack.enter_context(mock.patch('logfire._internal.auth.DEFAULT_FILE', auth_file)) prompt_mock = stack.enter_context( mock.patch('rich.prompt.Prompt.ask', side_effect=['fake_org', 'mytestproject1', '']) ) request_mocker = requests_mock.Mocker() stack.enter_context(request_mocker) # request_mocker.get('https://logfire-api.pydantic.dev/v1/info', json={'project_name': 'myproject'}) request_mocker.get('https://logfire-api.pydantic.dev/v1/writable-projects/', json=[]) request_mocker.get( 'https://logfire-api.pydantic.dev/v1/organizations/available-for-projects/', json=[{'organization_name': 'fake_org'}, {'organization_name': 'fake_org1'}], ) request_mocker.get( 'https://logfire-api.pydantic.dev/v1/info', json={'project_name': 'myproject', 'project_url': 'fake_project_url'}, ) request_mocker.get( 'https://logfire-api.pydantic.dev/v1/account/me', json={'default_organization': {'organization_name': 'fake_org1'}}, ) create_project_response = { 'json': { 'project_name': 'myproject', 'token': 'fake_token', 'project_url': 'fake_project_url', } } request_mocker.post( 'https://logfire-api.pydantic.dev/v1/organizations/fake_org/projects', [create_project_response], ) logfire.configure(send_to_logfire=True) wait_for_check_token_thread() assert prompt_mock.mock_calls == [ call( '\nTo create and use a new project, please provide the following information:\nSelect the organization to create the project in', choices=['fake_org', 'fake_org1'], default='fake_org1', ), call('Enter the project name', default=sanitize_project_name(tmp_dir_cwd.name)), call( 'Project initialized successfully. You will be able to view it at: fake_project_url\nPress Enter to continue' ), ] @pytest.mark.xdist_group(name='sequential') def test_create_new_project_selects_organization_with_no_tty(tmp_dir_cwd: Path, tmp_path: Path): """The organization-selection prompt already has `default=user_default_organization_name or organizations[0]` -- the same outcome a person pressing Enter would get -- so an exhausted stdin picks that organization instead of raising an `EOFError` traceback. """ auth_file = tmp_path / 'default.toml' auth_file.write_text( '[tokens."https://logfire-api.pydantic.dev"]\ntoken = "fake_user_token"\nexpiration = "2099-12-31T23:59:59"' ) with ExitStack() as stack: stack.enter_context(mock.patch('logfire._internal.auth.DEFAULT_FILE', auth_file)) prompt_mock = stack.enter_context( mock.patch('rich.prompt.Prompt.ask', side_effect=[EOFError, 'mytestproject1', '']) ) request_mocker = requests_mock.Mocker() stack.enter_context(request_mocker) request_mocker.get('https://logfire-api.pydantic.dev/v1/writable-projects/', json=[]) request_mocker.get( 'https://logfire-api.pydantic.dev/v1/organizations/available-for-projects/', json=[{'organization_name': 'fake_org'}, {'organization_name': 'fake_org1'}], ) request_mocker.get( 'https://logfire-api.pydantic.dev/v1/info', json={'project_name': 'myproject', 'project_url': 'fake_project_url'}, ) request_mocker.get( 'https://logfire-api.pydantic.dev/v1/account/me', json={'default_organization': {'organization_name': 'fake_org1'}}, ) create_project_response = { 'json': { 'project_name': 'myproject', 'token': 'fake_token', 'project_url': 'fake_project_url', } } # The default (`fake_org1`, from `account/me` above) is where the project must # land -- if the EOF fallback picked the WRONG organization, this mock would 404 # instead of the create call succeeding. request_mocker.post( 'https://logfire-api.pydantic.dev/v1/organizations/fake_org1/projects', [create_project_response], ) logfire.configure(send_to_logfire=True) wait_for_check_token_thread() assert prompt_mock.mock_calls == [ call( '\nTo create and use a new project, please provide the following information:\nSelect the organization to create the project in', choices=['fake_org', 'fake_org1'], default='fake_org1', ), call('Enter the project name', default=sanitize_project_name(tmp_dir_cwd.name)), call( 'Project initialized successfully. You will be able to view it at: fake_project_url\nPress Enter to continue' ), ] assert json.loads((tmp_dir_cwd / '.logfire/logfire_credentials.json').read_text()) == { **create_project_response['json'], 'logfire_api_url': 'https://logfire-api.pydantic.dev', } def test_initialize_project_completes_with_no_tty_at_the_final_prompt(tmp_dir_cwd: Path, tmp_path: Path): """`configure()` finishes even when stdin runs out at the very last prompt. That final "Press Enter to continue" discards its answer either way -- it exists to give a person a beat before moving on -- so an `EOFError` there must not turn an already-completed setup into a crash. This is the exact shape of a real failure: an agent piping just enough answers to satisfy the prompts it can see ahead of time (`printf 'y\\n1\\n' | python -c 'import logfire; logfire.configure()'`) and hitting an unhandled traceback on the one prompt it had no way to anticipate. """ auth_file = tmp_path / 'default.toml' auth_file.write_text( '[tokens."https://logfire-api.pydantic.dev"]\ntoken = "fake_user_token"\nexpiration = "2099-12-31T23:59:59"' ) with ExitStack() as stack: stack.enter_context(mock.patch('logfire._internal.auth.DEFAULT_FILE', auth_file)) confirm_mock = stack.enter_context(mock.patch('rich.prompt.Confirm.ask', side_effect=[True, True])) # Only two real answers, same as `printf 'y\n1\n'` -- the third prompt (the final # "Press Enter to continue") has nothing left to read. prompt_mock = stack.enter_context(mock.patch('rich.prompt.Prompt.ask', side_effect=['1', EOFError])) request_mocker = requests_mock.Mocker() stack.enter_context(request_mocker) request_mocker.get( 'https://logfire-api.pydantic.dev/v1/writable-projects/', json=[{'organization_name': 'fake_org', 'project_name': 'fake_project'}], ) request_mocker.get( 'https://logfire-api.pydantic.dev/v1/info', json={'project_name': 'myproject', 'project_url': 'fake_project_url'}, ) create_project_response = { 'json': { 'project_name': 'myproject', 'token': 'fake_token', 'project_url': 'fake_project_url', } } request_mocker.post( 'https://logfire-api.pydantic.dev/v1/organizations/fake_org/projects/fake_project/write-tokens/', [create_project_response], ) logfire.configure(send_to_logfire=True) wait_for_check_token_thread() assert confirm_mock.mock_calls == [call('Do you want to use one of your existing projects? ', default=True)] assert prompt_mock.mock_calls == [ call( "Please select one of the following projects by number (requires the 'write_token' permission):\n1. fake_org/fake_project\n", choices=['1'], default='1', ), call( 'Project initialized successfully. You will be able to view it at: fake_project_url\nPress Enter to continue', ), ] assert json.loads((tmp_dir_cwd / '.logfire/logfire_credentials.json').read_text()) == { **create_project_response['json'], 'logfire_api_url': 'https://logfire-api.pydantic.dev', } def test_initialize_project_uses_existing_projects_with_no_tty(tmp_dir_cwd: Path, tmp_path: Path): """ "Do you want to use one of your existing projects?" already has `default=True` -- the same outcome a person pressing Enter would get -- so an exhausted stdin reaches that same outcome (and then continues into `use_existing_project`) instead of an `EOFError` traceback on the very first prompt of the whole flow. """ auth_file = tmp_path / 'default.toml' auth_file.write_text( '[tokens."https://logfire-api.pydantic.dev"]\ntoken = "fake_user_token"\nexpiration = "2099-12-31T23:59:59"' ) with ExitStack() as stack: stack.enter_context(mock.patch('logfire._internal.auth.DEFAULT_FILE', auth_file)) confirm_mock = stack.enter_context(mock.patch('rich.prompt.Confirm.ask', side_effect=EOFError)) prompt_mock = stack.enter_context(mock.patch('rich.prompt.Prompt.ask', side_effect=['1', EOFError])) request_mocker = requests_mock.Mocker() stack.enter_context(request_mocker) request_mocker.get( 'https://logfire-api.pydantic.dev/v1/writable-projects/', json=[{'organization_name': 'fake_org', 'project_name': 'fake_project'}], ) request_mocker.get( 'https://logfire-api.pydantic.dev/v1/info', json={'project_name': 'myproject', 'project_url': 'fake_project_url'}, ) create_project_response = { 'json': { 'project_name': 'myproject', 'token': 'fake_token', 'project_url': 'fake_project_url', } } request_mocker.post( 'https://logfire-api.pydantic.dev/v1/organizations/fake_org/projects/fake_project/write-tokens/', [create_project_response], ) logfire.configure(send_to_logfire=True) wait_for_check_token_thread() # The `use_existing_project` prompt was still reached, proving the first Confirm # defaulted to True rather than skipping straight to project creation. assert prompt_mock.mock_calls[0] == call( "Please select one of the following projects by number (requires the 'write_token' permission):\n1. fake_org/fake_project\n", choices=['1'], default='1', ) assert confirm_mock.mock_calls == [call('Do you want to use one of your existing projects? ', default=True)] def test_create_new_project_confirms_the_organization_with_no_tty(tmp_dir_cwd: Path, tmp_path: Path): """The organization-creation "Continue?" confirm already has `default=True` -- the exact prompt a real user copying `logfire auth && python -c '...configure()'` out of the docs would hit with no terminal attached. An exhausted stdin reaches the same outcome pressing Enter would (create it) instead of an `EOFError` traceback. """ auth_file = tmp_path / 'default.toml' auth_file.write_text( '[tokens."https://logfire-api.pydantic.dev"]\ntoken = "fake_user_token"\nexpiration = "2099-12-31T23:59:59"' ) with ExitStack() as stack: stack.enter_context(mock.patch('logfire._internal.auth.DEFAULT_FILE', auth_file)) # Only the first Confirm ("use one of your existing projects?") has a real # answer; there are no existing projects, so it is never asked. The "Continue?" # confirm that matters here has nothing to read. confirm_mock = stack.enter_context(mock.patch('rich.prompt.Confirm.ask', side_effect=EOFError)) prompt_mock = stack.enter_context(mock.patch('rich.prompt.Prompt.ask', side_effect=['myproject', EOFError])) request_mocker = requests_mock.Mocker() stack.enter_context(request_mocker) request_mocker.get('https://logfire-api.pydantic.dev/v1/writable-projects/', json=[]) request_mocker.get( 'https://logfire-api.pydantic.dev/v1/organizations/available-for-projects/', json=[{'organization_name': 'fake_org'}], ) request_mocker.get( 'https://logfire-api.pydantic.dev/v1/info', json={'project_name': 'myproject', 'project_url': 'fake_project_url'}, ) create_project_response = { 'json': { 'project_name': 'myproject', 'token': 'fake_token', 'project_url': 'fake_project_url', } } request_mocker.post( 'https://logfire-api.pydantic.dev/v1/organizations/fake_org/projects', [create_project_response] ) logfire.configure(send_to_logfire=True) wait_for_check_token_thread() assert confirm_mock.mock_calls == [ call('The project will be created in the organization "fake_org". Continue?', default=True), ] assert prompt_mock.mock_calls == [ call('Enter the project name', default=sanitize_project_name(tmp_dir_cwd.name)), call( 'Project initialized successfully. You will be able to view it at: fake_project_url\nPress Enter to continue' ), ] assert json.loads((tmp_dir_cwd / '.logfire/logfire_credentials.json').read_text()) == { **create_project_response['json'], 'logfire_api_url': 'https://logfire-api.pydantic.dev', } def test_project_name_prompt_with_no_safe_default_and_no_tty_fails_with_guidance(tmp_dir_cwd: Path, tmp_path: Path): """A rejected project name has NO safe default left to fall back on ("Ellipsis" is a sentinel meaning "an answer is required", not a suggestion -- see the comment beside `project_name_default = ...`). So once the first name is rejected, an exhausted stdin must raise the same guidance `--non-interactive` would rather than silently retrying with a project literally named "Ellipsis". """ auth_file = tmp_path / 'default.toml' auth_file.write_text( '[tokens."https://logfire-api.pydantic.dev"]\ntoken = "fake_user_token"\nexpiration = "2099-12-31T23:59:59"' ) with ExitStack() as stack: stack.enter_context(mock.patch('logfire._internal.auth.DEFAULT_FILE', auth_file)) stack.enter_context(mock.patch('rich.prompt.Confirm.ask', side_effect=[True])) stack.enter_context(mock.patch('rich.prompt.Prompt.ask', side_effect=['existingprojectname', EOFError])) request_mocker = requests_mock.Mocker() stack.enter_context(request_mocker) request_mocker.get('https://logfire-api.pydantic.dev/v1/writable-projects/', json=[]) request_mocker.get( 'https://logfire-api.pydantic.dev/v1/organizations/available-for-projects/', json=[{'organization_name': 'fake_org'}], ) request_mocker.post( 'https://logfire-api.pydantic.dev/v1/organizations/fake_org/projects', [{'status_code': 409}], ) with pytest.raises(NonInteractiveError) as exc_info: logfire.configure(send_to_logfire=True) wait_for_check_token_thread() message = str(exc_info.value) assert "A project with the name 'existingprojectname' already exists" in message assert 'Cannot prompt because there is nothing left to read from stdin.' in message assert 'logfire projects new PROJECT_NAME --org fake_org' in message # No retry with the rejected name's sentinel default -- only the one doomed POST. create_requests = [r for r in request_mocker.request_history if r.method == 'POST'] assert len(create_requests) == 1 assert not (tmp_dir_cwd / '.logfire/logfire_credentials.json').exists() def test_send_to_logfire_true(tmp_path: Path) -> None: """ Test that with send_to_logfire=True, the logic is triggered to ask about creating a project. """ data_dir = tmp_path / 'logfire_data' auth_file = tmp_path / 'default.toml' auth_file.write_text( '[tokens."https://logfire-api.pydantic.dev"]\ntoken = "fake_user_token"\nexpiration = "2099-12-31T23:59:59"' ) with ExitStack() as stack: stack.enter_context(mock.patch('logfire._internal.auth.DEFAULT_FILE', auth_file)) stack.enter_context( mock.patch('logfire._internal.client.LogfireClient.get_user_projects', side_effect=RuntimeError('expected')) ) with pytest.raises(RuntimeError, match='^expected$'): configure(send_to_logfire=True, console=False, data_dir=data_dir) wait_for_check_token_thread() def test_send_to_logfire_false() -> None: """ Test that with send_to_logfire=False, that logic is NOT triggered. """ with mock.patch('logfire._internal.config.Confirm.ask', side_effect=RuntimeError): configure(send_to_logfire=False, console=False) def test_send_to_logfire_if_token_present() -> None: with mock.patch('logfire._internal.config.Confirm.ask', side_effect=RuntimeError): with requests_mock.Mocker() as request_mocker: configure(send_to_logfire='if-token-present', console=False) wait_for_check_token_thread() assert GLOBAL_CONFIG.token is None assert len(request_mocker.request_history) == 0 def test_send_to_logfire_if_token_present_empty() -> None: os.environ['LOGFIRE_TOKEN'] = '' try: with ExitStack() as stack: stack.enter_context(mock.patch('logfire._internal.config.Confirm.ask', side_effect=RuntimeError)) requests_mocker = stack.enter_context(requests_mock.Mocker()) configure(send_to_logfire='if-token-present', console=False) wait_for_check_token_thread() assert len(requests_mocker.request_history) == 0 finally: del os.environ['LOGFIRE_TOKEN'] def test_send_to_logfire_if_token_present_empty_via_env_var() -> None: with ( patch.dict( os.environ, {'LOGFIRE_TOKEN': '', 'LOGFIRE_SEND_TO_LOGFIRE': 'if-token-present'}, ), mock.patch( 'logfire._internal.config.Confirm.ask', side_effect=RuntimeError, ), requests_mock.Mocker() as requests_mocker, ): configure(console=False) wait_for_check_token_thread() assert len(requests_mocker.request_history) == 0 def test_send_to_logfire_if_token_present_empty_via_arg() -> None: with ExitStack() as stack: stack.enter_context(mock.patch('logfire._internal.config.Confirm.ask', side_effect=RuntimeError)) requests_mocker = stack.enter_context(requests_mock.Mocker()) configure(token='', send_to_logfire='if-token-present', console=False) wait_for_check_token_thread() assert len(requests_mocker.request_history) == 0 def wait_for_check_token_thread(): for thread in threading.enumerate(): if thread.name == 'check_logfire_token': # pragma: no cover thread.join() def test_token_check_is_skipped_on_aws_lambda(monkeypatch: pytest.MonkeyPatch) -> None: # Lambda freezes the environment after the init phase; a background token check frozen # mid-request would warn once thawed, and a synchronous check would slow every cold start. # Inside Lambda the check is skipped. The mocked /v1/info response is held back until # `release` is set, so a (wrongly) started background thread would still be alive and # visible when the assertions run. monkeypatch.setenv('AWS_LAMBDA_FUNCTION_NAME', 'my-function') release = threading.Event() def held_back_info(_request: Any, _context: Any) -> dict[str, str]: release.wait(timeout=5) return {'project_name': 'myproject', 'project_url': 'fake_project_url'} with requests_mock.Mocker() as request_mocker: request_mocker.get('https://logfire-us.pydantic.dev/v1/info', json=held_back_info) try: configure(token='foobar', send_to_logfire='if-token-present', console=False) assert not any(thread.name == 'check_logfire_token' for thread in threading.enumerate()) assert request_mocker.request_history == [] finally: release.set() def test_send_to_logfire_if_token_present_not_empty(capsys: pytest.CaptureFixture[str]) -> None: os.environ['LOGFIRE_TOKEN'] = 'foobar' try: with requests_mock.Mocker() as request_mocker: request_mocker.get( 'https://logfire-us.pydantic.dev/v1/info', json={'project_name': 'myproject', 'project_url': 'fake_project_url'}, ) configure(send_to_logfire='if-token-present') wait_for_check_token_thread() assert len(request_mocker.request_history) == 1 assert capsys.readouterr().err == 'Logfire project URL: fake_project_url\n' finally: del os.environ['LOGFIRE_TOKEN'] def test_send_to_logfire_if_token_present_not_empty_via_env_with_empty_arg(capsys: pytest.CaptureFixture[str]) -> None: os.environ['LOGFIRE_TOKEN'] = 'non_empty_token' try: with requests_mock.Mocker() as request_mocker: request_mocker.get( 'https://logfire-us.pydantic.dev/v1/info', json={'project_name': 'myproject', 'project_url': 'fake_project_url'}, ) configure(token='', send_to_logfire='if-token-present') wait_for_check_token_thread() assert len(request_mocker.request_history) == 1 assert capsys.readouterr().err == 'Logfire project URL: fake_project_url\n' finally: del os.environ['LOGFIRE_TOKEN'] def test_send_to_logfire_if_token_present_in_logfire_dir(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: creds_file = tmp_path / 'logfire_credentials.json' creds_file.write_text( """ { "token": "foobar", "project_name": "myproject", "project_url": "https://logfire-us.pydantic.dev", "logfire_api_url": "https://logfire-us.pydantic.dev" } """ ) with requests_mock.Mocker() as request_mocker: request_mocker.get( 'https://logfire-us.pydantic.dev/v1/info', json={'project_name': 'myproject', 'project_url': 'https://logfire-us.pydantic.dev'}, ) configure(send_to_logfire='if-token-present', data_dir=tmp_path) # Project link is printed immediately from credentials file (no need to wait for background thread) assert capsys.readouterr().err == 'Logfire project URL: https://logfire-us.pydantic.dev\n' wait_for_check_token_thread() assert len(request_mocker.request_history) == 1 def test_configure_unknown_token_region(capsys: pytest.CaptureFixture[str], tmp_path: Path) -> None: # Should default to us: with requests_mock.Mocker() as request_mocker: request_mocker.get( 'https://logfire-us.pydantic.dev/v1/info', json={'project_name': 'myproject', 'project_url': 'https://logfire-us.pydantic.dev'}, ) with pytest.warns(LogfireConfigWarning) as warns: configure(send_to_logfire='if-token-present', token='pylf_v1_unknownregion_foobarbaz', data_dir=tmp_path) # Inside the `pytest.warns` block so that any warning from the background # token-checking thread would be caught too: the token must warn exactly once. wait_for_check_token_thread() assert len(warns) == 1 assert str(warns[0].message) == snapshot( "Unknown region 'unknownregion' in Logfire token, falling back to the US region. Known regions: eu, us." ) assert len(request_mocker.request_history) == 1 assert capsys.readouterr().err == 'Logfire project URL: https://logfire-us.pydantic.dev\n' def test_load_creds_file_invalid_json_content(tmp_path: Path): creds_file = tmp_path / 'logfire_credentials.json' creds_file.write_text('invalid-data') with pytest.raises(LogfireConfigError, match='Invalid credentials file:'): logfire.configure(data_dir=tmp_path, send_to_logfire=True) def test_load_creds_file_invalid_json_content_with_token_present(tmp_path: Path, capsys: pytest.CaptureFixture[str]): creds_file = tmp_path / 'logfire_credentials.json' creds_file.write_text('invalid-data') with patch.dict(os.environ, {'LOGFIRE_TOKEN': 'fake_token'}), requests_mock.Mocker() as request_mocker: request_mocker.get( 'https://logfire-us.pydantic.dev/v1/info', json={'project_name': 'myproject', 'project_url': 'fake_project_url'}, ) logfire.configure(data_dir=tmp_path, send_to_logfire=True) wait_for_check_token_thread() assert len(request_mocker.request_history) == 1 assert request_mocker.request_history[0].headers['Authorization'] == 'fake_token' assert capsys.readouterr().err == 'Logfire project URL: fake_project_url\n' def test_load_creds_file_with_token_different_from_env(tmp_path: Path, capsys: pytest.CaptureFixture[str]): creds_file = tmp_path / 'logfire_credentials.json' creds_file.write_text( """ { "token": "foobar", "project_name": "myproject", "project_url": "https://logfire-us.pydantic.dev", "logfire_api_url": "https://logfire-us.pydantic.dev" } """ ) with patch.dict(os.environ, {'LOGFIRE_TOKEN': 'fake_token'}), requests_mock.Mocker() as request_mocker: request_mocker.get( 'https://logfire-us.pydantic.dev/v1/info', json={'project_name': 'myproject', 'project_url': 'fake_project_url'}, ) logfire.configure(data_dir=tmp_path, send_to_logfire=True) # not 'foobar' from the creds file. The token in the env var takes precedence. assert logfire.DEFAULT_LOGFIRE_INSTANCE.config.token == 'fake_token' wait_for_check_token_thread() assert len(request_mocker.request_history) == 1 assert request_mocker.request_history[0].headers['Authorization'] == 'fake_token' assert capsys.readouterr().err == 'Logfire project URL: fake_project_url\n' def test_load_creds_file_legacy_key(tmp_path: Path): creds_file = tmp_path / 'logfire_credentials.json' creds_file.write_text( """ { "dashboard_url": "http://dash.localhost:8000/test", "token":"test", "project_name": "test", "logfire_api_url": "http://dash.localhost:8000/" } """ ) cred = LogfireCredentials.load_creds_file(creds_dir=tmp_path) assert cred and cred.project_url == 'http://dash.localhost:8000/test' def test_load_creds_file_invalid_key(tmp_path: Path): creds_file = tmp_path / 'logfire_credentials.json' creds_file.write_text('{"test": "test"}') with pytest.raises(LogfireConfigError, match='Invalid credentials file:'): logfire.configure(data_dir=tmp_path, send_to_logfire=True) def test_initialize_credentials_from_token_unreachable(): with pytest.warns( UserWarning, match="Logfire API is unreachable, you may have trouble sending data. Error: Invalid URL '/v1/info': No scheme supplied.", ): LogfireConfig(advanced=logfire.AdvancedOptions(base_url='foo'))._initialize_credentials_from_token('some-token') # type: ignore def test_initialize_credentials_from_token_invalid_token(): with ExitStack() as stack: request_mocker = requests_mock.Mocker() stack.enter_context(request_mocker) request_mocker.get( 'https://logfire-us.pydantic.dev/v1/info', text='{"detail": "Invalid token"}', status_code=401 ) with pytest.warns(match='Logfire API returned status code 401. Detail: Invalid token'): LogfireConfig()._initialize_credentials_from_token('some-token') # type: ignore def test_initialize_credentials_from_token_unhealthy(): with ExitStack() as stack: request_mocker = requests_mock.Mocker() stack.enter_context(request_mocker) request_mocker.get('https://logfire-us.pydantic.dev/v1/info', text='Error', status_code=500) with pytest.warns( UserWarning, match='Logfire API returned status code 500, you may have trouble sending data.' ): LogfireConfig()._initialize_credentials_from_token('some-token') # type: ignore def test_configure_twice_no_warning(caplog: LogCaptureFixture): logfire.configure(send_to_logfire=False) assert not caplog.messages def test_configuration_span_not_emitted_by_default(config_kwargs: dict[str, Any], exporter: TestExporter): configure(**config_kwargs) assert not exporter.exported_spans_as_dict() def test_configuration_span_emitted_when_opted_in(config_kwargs: dict[str, Any], exporter: TestExporter): config_kwargs['advanced'].emit_configuration_span = True configure(**config_kwargs) assert exporter.exported_spans_as_dict(parse_json_attributes=True) == snapshot( [ { 'name': 'Logfire configured', 'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'parent': None, 'start_time': 1000000000, 'end_time': 1000000000, 'attributes': { 'logfire.span_type': 'log', 'logfire.level_num': 9, 'logfire.msg_template': 'Logfire configured', 'logfire.msg': 'Logfire configured', 'code.filepath': 'test_configure.py', 'code.function': 'test_configuration_span_emitted_when_opted_in', 'code.lineno': 123, 'logfire.config': { 'local': False, 'send_to_logfire': False, 'console_enabled': False, 'scrubbing_enabled': True, 'inspect_arguments': True, 'min_level': 0, 'add_baggage_to_attributes': False, 'distributed_tracing': True, 'head_sample_rate': 1.0, 'tail_sampling_enabled': False, 'code_source_set': False, 'variables_set': False, 'token_count': 0, 'api_key': False, 'service_name': False, 'service_version': True, 'environment': False, 'resource_attributes': 0, 'resource_detectors': 0, 'additional_span_processors': 1, }, 'logfire.package_versions': IsPartialDict({'logfire': IsStr()}), 'logfire.json_schema': { 'type': 'object', 'properties': { 'logfire.config': {'type': 'object'}, 'logfire.package_versions': {'type': 'object'}, }, }, 'logfire.disable_console_log': True, }, } ] ) def test_configuration_span_enabled_via_env_var(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setenv('LOGFIRE_EMIT_CONFIGURATION_SPAN', '1') configure(send_to_logfire=False, console=False, inspect_arguments=False) assert GLOBAL_CONFIG.advanced.emit_configuration_span is True def test_exit_open_spans_exports_suspended_generator_span_before_shutdown() -> None: script_path = Path(__file__).parent / 'import_used_for_tests' / 'open_span_at_shutdown.py' result = subprocess.run( [sys.executable, str(script_path)], capture_output=True, cwd=Path(__file__).parents[1], text=True, timeout=10, ) assert result.returncode == 0, result.stderr assert result.stdout == 'open span at shutdown\n' def test_send_to_logfire_under_pytest(): """ Test that the `send_to_logfire` parameter is set to False when running under pytest. """ assert 'PYTEST_VERSION' in os.environ logfire.configure() assert GLOBAL_CONFIG.send_to_logfire is False def test_default_exporters(monkeypatch: pytest.MonkeyPatch): monkeypatch.setattr(LogfireConfig, '_initialize_credentials_from_token', lambda *args: None) # type: ignore logfire.configure(send_to_logfire=True, token='foo') wait_for_check_token_thread() [console_span_processor, send_to_logfire_processor, pending_span_processor] = get_span_processors() assert isinstance(console_span_processor, SimpleSpanProcessor) assert isinstance(console_span_processor.span_exporter, ShowParentsConsoleSpanExporter) assert isinstance(send_to_logfire_processor, DynamicBatchSpanProcessor) assert isinstance(send_to_logfire_processor.span_exporter, RemovePendingSpansExporter) assert isinstance(pending_span_processor, PendingSpanProcessor) assert isinstance(pending_span_processor.processor, MainSpanProcessorWrapper) assert isinstance(pending_span_processor.processor.processor, SynchronousMultiSpanProcessor) assert pending_span_processor.processor.processor._span_processors == ( # type: ignore console_span_processor, send_to_logfire_processor, ) [logfire_metric_reader] = get_metric_readers() assert isinstance(logfire_metric_reader, PeriodicExportingMetricReader) assert isinstance(logfire_metric_reader._exporter, QuietMetricExporter) # type: ignore [console_log_processor, logfire_log_processor] = get_log_record_processors() assert isinstance(console_log_processor, SimpleLogRecordProcessor) assert isinstance(console_log_processor._exporter, ConsoleLogExporter) # type: ignore assert console_log_processor._exporter.span_exporter is console_span_processor.span_exporter # type: ignore exporter = get_batch_log_exporter(logfire_log_processor) assert isinstance(exporter, QuietLogExporter) assert isinstance(exporter.exporter, OTLPLogExporter) def test_custom_exporters(): custom_span_processor = SimpleSpanProcessor(ConsoleSpanExporter()) custom_metric_reader = InMemoryMetricReader() custom_log_processor = SynchronousMultiLogRecordProcessor() logfire.configure( send_to_logfire=False, console=False, additional_span_processors=[custom_span_processor], metrics=logfire.MetricsOptions(additional_readers=[custom_metric_reader]), advanced=logfire.AdvancedOptions(log_record_processors=[custom_log_processor]), ) [custom_span_processor2] = get_span_processors() assert custom_span_processor2 is custom_span_processor [custom_metric_reader2] = get_metric_readers() assert custom_metric_reader2 is custom_metric_reader [custom_log_processor2] = get_log_record_processors() assert custom_log_processor2 is custom_log_processor def test_otel_exporter_otlp_endpoint_env_var(): # Setting this env var creates an OTLPSpanExporter and an OTLPMetricExporter with patch.dict(os.environ, {'OTEL_EXPORTER_OTLP_ENDPOINT': 'otel_endpoint'}): logfire.configure(send_to_logfire=False, console=False) [otel_processor] = get_span_processors() exporter = get_batch_span_exporter(otel_processor) assert isinstance(exporter, OTLPSpanExporter) assert exporter._endpoint == 'otel_endpoint/v1/traces' # type: ignore [otel_metric_reader] = get_metric_readers() assert isinstance(otel_metric_reader, PeriodicExportingMetricReader) assert isinstance(otel_metric_reader._exporter, OTLPMetricExporter) # type: ignore assert otel_metric_reader._exporter._endpoint == 'otel_endpoint/v1/metrics' # type: ignore [otel_log_processor] = get_log_record_processors() log_exporter = get_batch_log_exporter(otel_log_processor) assert isinstance(log_exporter, OTLPLogExporter) assert log_exporter._endpoint == 'otel_endpoint/v1/logs' # type: ignore def test_otel_traces_exporter_env_var(): # Setting OTEL_TRACES_EXPORTER to something other than otlp prevents creating an OTLPSpanExporter # Same for OTEL_LOGS_EXPORTER with patch.dict( os.environ, { 'OTEL_EXPORTER_OTLP_ENDPOINT': 'otel_endpoint2', 'OTEL_TRACES_EXPORTER': 'grpc', 'OTEL_LOGS_EXPORTER': 'none', }, ): logfire.configure(send_to_logfire=False, console=False) assert len(list(get_span_processors())) == 0 assert len(list(get_log_record_processors())) == 0 [otel_metric_reader] = get_metric_readers() assert isinstance(otel_metric_reader, PeriodicExportingMetricReader) assert isinstance(otel_metric_reader._exporter, OTLPMetricExporter) # type: ignore assert otel_metric_reader._exporter._endpoint == 'otel_endpoint2/v1/metrics' # type: ignore def test_otel_metrics_exporter_env_var(): # Setting OTEL_METRICS_EXPORTER to something other than otlp prevents creating an OTLPMetricExporter with patch.dict(os.environ, {'OTEL_EXPORTER_OTLP_ENDPOINT': 'otel_endpoint3', 'OTEL_METRICS_EXPORTER': 'none'}): logfire.configure(send_to_logfire=False, console=False) [otel_processor] = get_span_processors() exporter = get_batch_span_exporter(otel_processor) assert isinstance(exporter, OTLPSpanExporter) assert exporter._endpoint == 'otel_endpoint3/v1/traces' # type: ignore assert len(list(get_metric_readers())) == 0 def test_otel_logs_exporter_env_var(): # Setting OTEL_LOGS_EXPORTER to something other than otlp prevents creating an OTLPLogExporter with patch.dict(os.environ, {'OTEL_EXPORTER_OTLP_ENDPOINT': 'otel_endpoint4', 'OTEL_LOGS_EXPORTER': 'none'}): logfire.configure(send_to_logfire=False, console=False) [otel_processor] = get_span_processors() exporter = get_batch_span_exporter(otel_processor) assert isinstance(exporter, OTLPSpanExporter) assert exporter._endpoint == 'otel_endpoint4/v1/traces' # type: ignore assert len(list(get_log_record_processors())) == 0 def test_otel_exporter_otlp_traces_endpoint_env_var(): # Setting just OTEL_EXPORTER_OTLP_TRACES_ENDPOINT only creates an OTLPSpanExporter with patch.dict(os.environ, {'OTEL_EXPORTER_OTLP_TRACES_ENDPOINT': 'otel_traces_endpoint'}): logfire.configure(send_to_logfire=False, console=False) [otel_processor] = get_span_processors() exporter = get_batch_span_exporter(otel_processor) assert isinstance(exporter, OTLPSpanExporter) assert exporter._endpoint == 'otel_traces_endpoint' # type: ignore assert len(list(get_metric_readers())) == 0 assert len(list(get_log_record_processors())) == 0 def test_otel_exporter_otlp_metrics_endpoint_env_var(): # Setting just OTEL_EXPORTER_OTLP_METRICS_ENDPOINT only creates an OTLPMetricExporter with patch.dict(os.environ, {'OTEL_EXPORTER_OTLP_METRICS_ENDPOINT': 'otel_metrics_endpoint'}): logfire.configure(send_to_logfire=False, console=False) assert len(list(get_span_processors())) == 0 assert len(list(get_log_record_processors())) == 0 [otel_metric_reader] = get_metric_readers() assert isinstance(otel_metric_reader, PeriodicExportingMetricReader) assert isinstance(otel_metric_reader._exporter, OTLPMetricExporter) # type: ignore assert otel_metric_reader._exporter._endpoint == 'otel_metrics_endpoint' # type: ignore def test_otel_exporter_otlp_logs_endpoint_env_var(): # Setting just OTEL_EXPORTER_OTLP_LOGS_ENDPOINT only creates an OTLPLogExporter with patch.dict(os.environ, {'OTEL_EXPORTER_OTLP_LOGS_ENDPOINT': 'otel_logs_endpoint'}): logfire.configure(send_to_logfire=False, console=False) assert len(list(get_span_processors())) == 0 assert len(list(get_metric_readers())) == 0 [otel_log_processor] = get_log_record_processors() exporter = get_batch_log_exporter(otel_log_processor) assert isinstance(exporter, OTLPLogExporter) assert exporter._endpoint == 'otel_logs_endpoint' # type: ignore def test_metrics_false(monkeypatch: pytest.MonkeyPatch): monkeypatch.setattr(LogfireConfig, '_initialize_credentials_from_token', lambda *args: None) # type: ignore with patch.dict(os.environ, {'OTEL_EXPORTER_OTLP_METRICS_ENDPOINT': 'otel_metrics_endpoint'}): logfire.configure(send_to_logfire=True, token='foo', metrics=False) wait_for_check_token_thread() assert isinstance(get_meter_provider().provider, NoOpMeterProvider) # type: ignore def get_span_processors() -> Iterable[SpanProcessor]: [root] = get_tracer_provider().provider._active_span_processor._span_processors # type: ignore assert isinstance(root, CheckSuppressInstrumentationProcessorWrapper) assert isinstance(root.processor, MainSpanProcessorWrapper) assert isinstance(root.processor.processor, SynchronousMultiSpanProcessor) result = list(root.processor.processor._span_processors) # type: ignore assert isinstance(result[0], DirectBaggageAttributesSpanProcessor) return result[1:] def get_metric_readers() -> Iterable[object]: provider = get_meter_provider().provider # type: ignore result = provider._logfire_metric_readers # type: ignore try: # This only works on older OTel versions and is just a sanity check now. assert result == provider._sdk_config.metric_readers # type: ignore except AttributeError: pass return result # type: ignore def get_log_record_processors() -> Iterable[LogRecordProcessor]: [processor] = get_logger_provider().provider._multi_log_record_processor._log_record_processors # type: ignore assert isinstance(processor, CheckSuppressInstrumentationLogProcessorWrapper) processor = processor.processor assert isinstance(processor, MainLogProcessorWrapper) processor = processor.processor assert isinstance(processor, SynchronousMultiLogRecordProcessor) return processor._log_record_processors # type: ignore def test_dynamic_module_ignored_in_ensure_flush_after_aws_lambda( config_kwargs: dict[str, Any], capsys: pytest.CaptureFixture[str] ): from tests.import_used_for_tests.module_with_getattr import module_with_getattr_value assert module_with_getattr_value == 'module_with_getattr_value' logfire.configure(**config_kwargs) assert capsys.readouterr().err == '' def test_unknown_kwargs(): with inline_snapshot.extra.raises(snapshot("TypeError: configure() got an unexpected keyword argument 'foo'")): logfire.configure(foo=1) # type: ignore def test_environment(config_kwargs: dict[str, Any], exporter: TestExporter): configure(**config_kwargs, service_version='1.2.3', environment='production') logfire.info('test1') assert exporter.exported_spans_as_dict(include_resources=True) == snapshot( [ { 'name': 'test1', 'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'parent': None, 'start_time': 1000000000, 'end_time': 1000000000, 'attributes': { 'logfire.span_type': 'log', 'logfire.level_num': 9, 'logfire.msg_template': 'test1', 'logfire.msg': 'test1', 'code.filepath': 'test_configure.py', 'code.function': 'test_environment', 'code.lineno': 123, }, 'resource': { 'attributes': { 'service.instance.id': '00000000000000000000000000000000', 'telemetry.sdk.language': 'python', 'telemetry.sdk.name': 'opentelemetry', 'telemetry.sdk.version': '0.0.0', 'logfire.version': VERSION, 'service.name': 'unknown_service', 'process.pid': 1234, 'process.runtime.name': 'cpython', 'process.runtime.version': IsStr(regex=PROCESS_RUNTIME_VERSION_REGEX), 'process.runtime.description': sys.version, 'host.name': IsStr(), 'host.arch': IsStr(), 'os.type': IsStr(), 'os.version': IsStr(), 'service.version': '1.2.3', 'deployment.environment.name': 'production', } }, } ] ) def test_code_source(config_kwargs: dict[str, Any], exporter: TestExporter): configure( **config_kwargs, service_version='1.2.3', code_source=CodeSource( repository='https://github.com/pydantic/logfire', revision='main', root_path='logfire', ), ) logfire.info('test1') assert exporter.exported_spans_as_dict(include_resources=True) == snapshot( [ { 'name': 'test1', 'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'parent': None, 'start_time': 1000000000, 'end_time': 1000000000, 'attributes': { 'logfire.span_type': 'log', 'logfire.level_num': 9, 'logfire.msg_template': 'test1', 'logfire.msg': 'test1', 'code.filepath': 'test_configure.py', 'code.function': 'test_code_source', 'code.lineno': 123, }, 'resource': { 'attributes': { 'service.instance.id': '00000000000000000000000000000000', 'telemetry.sdk.language': 'python', 'telemetry.sdk.name': 'opentelemetry', 'telemetry.sdk.version': '0.0.0', 'logfire.version': VERSION, 'service.name': 'unknown_service', 'process.pid': 1234, 'process.runtime.name': 'cpython', 'process.runtime.version': IsStr(regex=PROCESS_RUNTIME_VERSION_REGEX), 'process.runtime.description': sys.version, 'host.name': IsStr(), 'host.arch': IsStr(), 'os.type': IsStr(), 'os.version': IsStr(), 'logfire.code.root_path': 'logfire', 'logfire.code.work_dir': os.getcwd(), 'vcs.repository.url.full': 'https://github.com/pydantic/logfire', 'vcs.repository.ref.revision': 'main', 'service.version': '1.2.3', } }, } ] ) def test_code_source_without_root_path(config_kwargs: dict[str, Any], exporter: TestExporter): configure( **config_kwargs, service_version='1.2.3', code_source=CodeSource( repository='https://github.com/pydantic/logfire', revision='main', ), ) logfire.info('test1') assert exporter.exported_spans_as_dict(include_resources=True) == snapshot( [ { 'name': 'test1', 'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'parent': None, 'start_time': 1000000000, 'end_time': 1000000000, 'attributes': { 'logfire.span_type': 'log', 'logfire.level_num': 9, 'logfire.msg_template': 'test1', 'logfire.msg': 'test1', 'code.filepath': 'test_configure.py', 'code.function': 'test_code_source_without_root_path', 'code.lineno': 123, }, 'resource': { 'attributes': { 'service.instance.id': '00000000000000000000000000000000', 'telemetry.sdk.language': 'python', 'telemetry.sdk.name': 'opentelemetry', 'telemetry.sdk.version': '0.0.0', 'logfire.version': VERSION, 'service.name': 'unknown_service', 'process.pid': 1234, 'process.runtime.name': 'cpython', 'process.runtime.version': IsStr(regex=PROCESS_RUNTIME_VERSION_REGEX), 'process.runtime.description': sys.version, 'host.name': IsStr(), 'host.arch': IsStr(), 'os.type': IsStr(), 'os.version': IsStr(), 'logfire.code.work_dir': os.getcwd(), 'vcs.repository.url.full': 'https://github.com/pydantic/logfire', 'vcs.repository.ref.revision': 'main', 'service.version': '1.2.3', } }, } ] ) def test_local_config(exporter: TestExporter, config_kwargs: dict[str, Any]): local_exporter = TestExporter() config_kwargs['additional_span_processors'] = [SimpleSpanProcessor(local_exporter)] local_logfire = logfire.configure(**config_kwargs, local=True) assert local_logfire != logfire.DEFAULT_LOGFIRE_INSTANCE assert local_logfire.config != logfire.DEFAULT_LOGFIRE_INSTANCE.config logfire.info('test1') local_logfire.info('test2') assert exporter.exported_spans_as_dict() == snapshot( [ { 'name': 'test1', 'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'parent': None, 'start_time': 1000000000, 'end_time': 1000000000, 'attributes': { 'logfire.span_type': 'log', 'logfire.level_num': 9, 'logfire.msg_template': 'test1', 'logfire.msg': 'test1', 'code.filepath': 'test_configure.py', 'code.function': 'test_local_config', 'code.lineno': 123, }, } ] ) assert local_exporter.exported_spans_as_dict() == snapshot( [ { 'name': 'test2', 'context': { 'trace_id': 2, 'span_id': 2, 'is_remote': False, }, 'parent': None, 'start_time': 2000000000, 'end_time': 2000000000, 'attributes': { 'logfire.span_type': 'log', 'logfire.level_num': 9, 'logfire.msg_template': 'test2', 'logfire.msg': 'test2', 'code.filepath': 'test_configure.py', 'code.function': 'test_local_config', 'code.lineno': 123, }, } ] ) def test_distributed_tracing_default(exporter: TestExporter, config_kwargs: dict[str, Any]): config_kwargs['distributed_tracing'] = None logfire.configure(**config_kwargs) assert isinstance(get_global_textmap(), WarnOnExtractTraceContextPropagator) assert get_global_textmap().fields == {'baggage', 'traceparent', 'tracestate'} with logfire.span('span1'): ctx = propagate.get_context() with propagate.attach_context(ctx): logfire.info('test1') with inline_snapshot.extra.warns( snapshot( [ 'RuntimeWarning: Found propagated trace context. See https://logfire.pydantic.dev/docs/how-to-guides/distributed-tracing/#unintentional-distributed-tracing.' ] ) ): with propagate.attach_context(ctx, third_party=True): logfire.info('test2') # Only warn once. with propagate.attach_context(ctx, third_party=True): logfire.info('test3') assert exporter.exported_spans_as_dict() == snapshot( [ { 'name': 'span1', 'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'parent': None, 'start_time': 1000000000, 'end_time': 2000000000, 'attributes': { 'code.filepath': 'test_configure.py', 'code.function': 'test_distributed_tracing_default', 'code.lineno': 123, 'logfire.msg_template': 'span1', 'logfire.msg': 'span1', 'logfire.span_type': 'span', }, }, { 'name': 'test1', 'context': {'trace_id': 1, 'span_id': 3, 'is_remote': False}, 'parent': {'trace_id': 1, 'span_id': 1, 'is_remote': True}, 'start_time': 3000000000, 'end_time': 3000000000, 'attributes': { 'logfire.span_type': 'log', 'logfire.level_num': 9, 'logfire.msg_template': 'test1', 'logfire.msg': 'test1', 'code.filepath': 'test_configure.py', 'code.function': 'test_distributed_tracing_default', 'code.lineno': 123, }, }, { 'name': 'Found propagated trace context. See https://logfire.pydantic.dev/docs/how-to-guides/distributed-tracing/#unintentional-distributed-tracing.', 'context': {'trace_id': 2, 'span_id': 4, 'is_remote': False}, 'parent': None, 'start_time': 4000000000, 'end_time': 4000000000, 'attributes': { 'logfire.span_type': 'log', 'logfire.level_num': 13, 'logfire.msg_template': 'Found propagated trace context. See https://logfire.pydantic.dev/docs/how-to-guides/distributed-tracing/#unintentional-distributed-tracing.', 'logfire.msg': 'Found propagated trace context. See https://logfire.pydantic.dev/docs/how-to-guides/distributed-tracing/#unintentional-distributed-tracing.', 'code.filepath': 'test_configure.py', 'code.function': 'test_distributed_tracing_default', 'code.lineno': 123, }, }, { 'name': 'test2', 'context': {'trace_id': 1, 'span_id': 5, 'is_remote': False}, 'parent': {'trace_id': 1, 'span_id': 1, 'is_remote': True}, 'start_time': 5000000000, 'end_time': 5000000000, 'attributes': { 'logfire.span_type': 'log', 'logfire.level_num': 9, 'logfire.msg_template': 'test2', 'logfire.msg': 'test2', 'code.filepath': 'test_configure.py', 'code.function': 'test_distributed_tracing_default', 'code.lineno': 123, }, }, { 'name': 'test3', 'context': {'trace_id': 1, 'span_id': 6, 'is_remote': False}, 'parent': {'trace_id': 1, 'span_id': 1, 'is_remote': True}, 'start_time': 6000000000, 'end_time': 6000000000, 'attributes': { 'logfire.span_type': 'log', 'logfire.level_num': 9, 'logfire.msg_template': 'test3', 'logfire.msg': 'test3', 'code.filepath': 'test_configure.py', 'code.function': 'test_distributed_tracing_default', 'code.lineno': 123, }, }, ] ) def test_distributed_tracing_enabled(exporter: TestExporter): assert isinstance(get_global_textmap(), CompositePropagator) assert get_global_textmap().fields == {'baggage', 'traceparent', 'tracestate'} with logfire.span('span1'): ctx = propagate.get_context() with propagate.attach_context(ctx): logfire.info('test1') with propagate.attach_context(ctx, third_party=True): logfire.info('test2') assert exporter.exported_spans_as_dict() == snapshot( [ { 'name': 'span1', 'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'parent': None, 'start_time': 1000000000, 'end_time': 2000000000, 'attributes': { 'code.filepath': 'test_configure.py', 'code.function': 'test_distributed_tracing_enabled', 'code.lineno': 123, 'logfire.msg_template': 'span1', 'logfire.msg': 'span1', 'logfire.span_type': 'span', }, }, { 'name': 'test1', 'context': {'trace_id': 1, 'span_id': 3, 'is_remote': False}, 'parent': {'trace_id': 1, 'span_id': 1, 'is_remote': True}, 'start_time': 3000000000, 'end_time': 3000000000, 'attributes': { 'logfire.span_type': 'log', 'logfire.level_num': 9, 'logfire.msg_template': 'test1', 'logfire.msg': 'test1', 'code.filepath': 'test_configure.py', 'code.function': 'test_distributed_tracing_enabled', 'code.lineno': 123, }, }, { 'name': 'test2', 'context': {'trace_id': 1, 'span_id': 4, 'is_remote': False}, 'parent': {'trace_id': 1, 'span_id': 1, 'is_remote': True}, 'start_time': 4000000000, 'end_time': 4000000000, 'attributes': { 'logfire.span_type': 'log', 'logfire.level_num': 9, 'logfire.msg_template': 'test2', 'logfire.msg': 'test2', 'code.filepath': 'test_configure.py', 'code.function': 'test_distributed_tracing_enabled', 'code.lineno': 123, }, }, ] ) def test_distributed_tracing_disabled(exporter: TestExporter, config_kwargs: dict[str, Any]): config_kwargs['distributed_tracing'] = False logfire.configure(**config_kwargs) assert isinstance(get_global_textmap(), NoExtractTraceContextPropagator) assert get_global_textmap().fields == {'baggage', 'traceparent', 'tracestate'} with logfire.span('span1'): ctx = propagate.get_context() with propagate.attach_context(ctx): logfire.info('test1') with propagate.attach_context(ctx, third_party=True): logfire.info('test2') assert exporter.exported_spans_as_dict() == snapshot( [ { 'name': 'span1', 'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'parent': None, 'start_time': 1000000000, 'end_time': 2000000000, 'attributes': { 'code.filepath': 'test_configure.py', 'code.function': 'test_distributed_tracing_disabled', 'code.lineno': 123, 'logfire.msg_template': 'span1', 'logfire.msg': 'span1', 'logfire.span_type': 'span', }, }, { 'name': 'test1', 'context': {'trace_id': 1, 'span_id': 3, 'is_remote': False}, 'parent': {'trace_id': 1, 'span_id': 1, 'is_remote': True}, 'start_time': 3000000000, 'end_time': 3000000000, 'attributes': { 'logfire.span_type': 'log', 'logfire.level_num': 9, 'logfire.msg_template': 'test1', 'logfire.msg': 'test1', 'code.filepath': 'test_configure.py', 'code.function': 'test_distributed_tracing_disabled', 'code.lineno': 123, }, }, { 'name': 'test2', 'context': {'trace_id': 2, 'span_id': 4, 'is_remote': False}, 'parent': None, 'start_time': 4000000000, 'end_time': 4000000000, 'attributes': { 'logfire.span_type': 'log', 'logfire.level_num': 9, 'logfire.msg_template': 'test2', 'logfire.msg': 'test2', 'code.filepath': 'test_configure.py', 'code.function': 'test_distributed_tracing_disabled', 'code.lineno': 123, }, }, ] ) def test_quiet_span_exporter(caplog: LogCaptureFixture): class ConnectionErrorExporter(SpanExporter): def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult: raise requests.exceptions.ConnectionError() exporter = QuietSpanExporter(ConnectionErrorExporter()) assert exporter.export([]) == SpanExportResult.FAILURE assert not caplog.messages def test_staging_token_regions(): assert get_base_url_from_token('pylf_v1_stagingeu_123456') == 'https://logfire-eu.pydantic.info' assert get_base_url_from_token('pylf_v1_stagingus_123456') == 'https://logfire-us.pydantic.info' # Backend routing must not depend on validation of the evolving token suffix format. assert ( get_base_url_from_token( 'pylf_v2_stagingeu_9F9BA85A-B759-4181-9527-D812E03F9F7F_0kYhc414Ys2FNDRdt5vFB05xFx5NjVcbcBMy4Kp6PH0W' ) == get_base_url_from_token( 'pylf_v2_stagingeu_9F9BA85AB759181-9527-D81^&*%*&^%*&^ 2E03F9F7F_0kYhc414Ys2FNDRdt5vFBcbcBMy4Kp6PH0W' ) == 'https://logfire-eu.pydantic.info' ) def test_known_token_regions_do_not_warn(): with warnings.catch_warnings(): warnings.simplefilter('error') assert get_base_url_from_token('pylf_v1_us_123456') == 'https://logfire-us.pydantic.dev' assert get_base_url_from_token('pylf_v1_eu_123456') == 'https://logfire-eu.pydantic.dev' # Tokens predating regions have no region segment and must keep working silently. assert get_base_url_from_token('legacy_token_no_region') == 'https://logfire-us.pydantic.dev' def test_unknown_token_region_warns_by_default(): with pytest.warns(LogfireConfigWarning) as warns: assert get_base_url_from_token('pylf_v1_unknownregion_123456') == snapshot('https://logfire-us.pydantic.dev') assert str(warns[0].message) == snapshot( "Unknown region 'unknownregion' in Logfire token, falling back to the US region. Known regions: eu, us." ) def test_generate_base_url_warns_about_unknown_region_by_default(): # All `generate_base_url` callers are configuration paths, so they all warn consistently: # the exporter setup, the variables provider, lazy variable init and credential validation. with pytest.warns(LogfireConfigWarning) as warns: assert ( logfire.AdvancedOptions().generate_base_url('pylf_v1_unknownregion_123456') == 'https://logfire-us.pydantic.dev' ) assert str(warns[0].message) == snapshot( "Unknown region 'unknownregion' in Logfire token, falling back to the US region. Known regions: eu, us." ) def test_generate_base_url_with_explicit_base_url_does_not_warn(): # An explicit base_url overrides region routing entirely, so there's nothing to warn about. with warnings.catch_warnings(): warnings.simplefilter('error') advanced = logfire.AdvancedOptions(base_url='https://my-proxy.example.com') assert advanced.generate_base_url('pylf_v1_unknownregion_123456') == 'https://my-proxy.example.com' def test_unknown_token_region_warning_can_be_disabled(): with warnings.catch_warnings(): warnings.simplefilter('error') assert ( get_base_url_from_token('pylf_v1_unknownregion_123456', warn_unknown_region=False) == 'https://logfire-us.pydantic.dev' ) def test_multiple_tokens_list(monkeypatch: pytest.MonkeyPatch) -> None: """Test that multiple tokens can be provided as a list and create multiple export pipelines.""" monkeypatch.setattr(LogfireConfig, '_initialize_credentials_from_token', lambda *args: None) # type: ignore configure( token=['pylf_v1_us_token1', 'pylf_v1_us_token2'], send_to_logfire=True, console=False, ) wait_for_check_token_thread() # Check that both tokens are stored assert GLOBAL_CONFIG.token == ['pylf_v1_us_token1', 'pylf_v1_us_token2'] # Check that TWO span processors are created (one per token) span_processors = list(get_span_processors()) # Should have 2 DynamicBatchSpanProcessors + 1 PendingSpanProcessor assert len(span_processors) == 3 token1_span_processor, token2_span_processor, pending_processor = span_processors assert isinstance(token1_span_processor, DynamicBatchSpanProcessor) assert isinstance(token2_span_processor, DynamicBatchSpanProcessor) assert isinstance(pending_processor, PendingSpanProcessor) # Verify each span exporter has the correct authorization header token1_exporter = token1_span_processor.span_exporter token2_exporter = token2_span_processor.span_exporter # Unwrap to get to the OTLP exporter (WrapperSpanExporter uses wrapped_exporter attribute) while hasattr(token1_exporter, 'wrapped_exporter'): # type: ignore token1_exporter = token1_exporter.wrapped_exporter # type: ignore while hasattr(token2_exporter, 'wrapped_exporter'): # type: ignore token2_exporter = token2_exporter.wrapped_exporter # type: ignore assert token1_exporter._session.headers['Authorization'] == 'pylf_v1_us_token1' # type: ignore assert token2_exporter._session.headers['Authorization'] == 'pylf_v1_us_token2' # type: ignore # Check that TWO metric readers are created (one per token) metric_readers = list(get_metric_readers()) assert len(metric_readers) == 2 for reader in metric_readers: assert isinstance(reader, PeriodicExportingMetricReader) assert isinstance(reader._exporter, QuietMetricExporter) # type: ignore # Check that TWO log processors are created (one per token) log_processors = list(get_log_record_processors()) assert len(log_processors) == 2 for processor in log_processors: exporter = get_batch_log_exporter(processor) assert isinstance(exporter, QuietLogExporter) assert isinstance(exporter.exporter, OTLPLogExporter) def test_multiple_tokens_env_var(monkeypatch: pytest.MonkeyPatch) -> None: """Test that multiple tokens can be provided via comma-separated environment variable.""" monkeypatch.setattr(LogfireConfig, '_initialize_credentials_from_token', lambda *args: None) # type: ignore os.environ['LOGFIRE_TOKEN'] = 'pylf_v1_us_token1, pylf_v1_us_token2' try: configure( send_to_logfire=True, console=False, ) wait_for_check_token_thread() # Check that both tokens are stored (spaces trimmed) assert GLOBAL_CONFIG.token == ['pylf_v1_us_token1', 'pylf_v1_us_token2'] # Verify multiple export pipelines are created span_processors = list(get_span_processors()) # Should have 2 DynamicBatchSpanProcessors + 1 PendingSpanProcessor assert len(span_processors) == 3 metric_readers = list(get_metric_readers()) assert len(metric_readers) == 2 log_processors = list(get_log_record_processors()) assert len(log_processors) == 2 finally: del os.environ['LOGFIRE_TOKEN'] def test_extract_list_of_str(): """Test extract_list_of_str function for various inputs.""" # Empty sequences assert extract_list_of_str([]) is None assert extract_list_of_str(()) is None # Single string token assert extract_list_of_str('token1') == ['token1'] # Comma-separated string with multiple tokens assert extract_list_of_str('token1,token2') == ['token1', 'token2'] # Comma-separated string with spaces (should be trimmed) assert extract_list_of_str('token1, token2') == ['token1', 'token2'] assert extract_list_of_str(' token1 , token2 ') == ['token1', 'token2'] # String with only commas and spaces assert extract_list_of_str(',, ,') is None # Empty string assert extract_list_of_str('') is None # Non-empty list assert extract_list_of_str(['token1', 'token2']) == ['token1', 'token2'] # List with empty strings # The filtering of empty strings happens in extract_list_of_str assert extract_list_of_str(['token1', '', 'token2']) == ['token1', 'token2'] def test_normalize_token(): """Test normalize_token function for various inputs.""" # None returns None assert normalize_token(None) is None # Empty string returns None assert normalize_token('') is None # Empty sequences return None assert normalize_token([]) is None assert normalize_token(()) is None # String with only commas returns None assert normalize_token(',,,,') is None assert normalize_token(',, ,') is None # Single token string returns the token as a string (not a list) assert normalize_token('token1') == 'token1' # Single token with surrounding whitespace assert normalize_token(' token1 ') == 'token1' # Multiple tokens returns a list assert normalize_token('token1,token2') == ['token1', 'token2'] assert normalize_token('token1, token2, token3') == ['token1', 'token2', 'token3'] # Tokens with empty entries filtered out assert normalize_token('token1,,token2') == ['token1', 'token2'] assert normalize_token(',token1,') == 'token1' assert normalize_token(',,token1,,token2,,') == ['token1', 'token2'] # Whitespace around tokens is trimmed assert normalize_token(' token1 , token2 ') == ['token1', 'token2'] # Single-element list returns string assert normalize_token(['token1']) == 'token1' # Multi-element list returns list assert normalize_token(['token1', 'token2']) == ['token1', 'token2'] # Tuple input assert normalize_token(('token1',)) == 'token1' assert normalize_token(('token1', 'token2')) == ['token1', 'token2'] def test_host_resource_attributes(): # Check that we're copying OTel accurately while avoiding the private import outside tests. from opentelemetry.sdk.resources import _HostResourceDetector # pyright: ignore[reportPrivateUsage] assert config_module.host_resource_attributes() == _HostResourceDetector().detect().attributes
from __future__ import annotations
import dataclasses
import getpass
import inspect
import json
import os
import pickle
import signal
import subprocess
import sys
import threading
import warnings
from collections.abc import Callable, Iterable, Sequence
from contextlib import ExitStack
from io import StringIO
from pathlib import Path
from time import sleep, time
from typing import Any
from unittest import mock
from unittest.mock import call, patch
import inline_snapshot.extra
import pytest
import requests.exceptions
import requests_mock
from dirty_equals import IsPartialDict, IsStr
from inline_snapshot import snapshot
from opentelemetry._logs import LogRecord, get_logger, get_logger_provider
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.metrics import NoOpMeterProvider, get_meter_provider
from opentelemetry.propagate import get_global_textmap
from opentelemetry.propagators.composite import CompositePropagator
from opentelemetry.sdk._logs import LogRecordProcessor
from opentelemetry.sdk._logs._internal import SynchronousMultiLogRecordProcessor
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor, LogRecordExporter, SimpleLogRecordProcessor
from opentelemetry.sdk.metrics.export import InMemoryMetricReader, PeriodicExportingMetricReader
from opentelemetry.sdk.resources import Resource, ResourceDetector
from opentelemetry.sdk.trace import ReadableSpan, SpanProcessor, SynchronousMultiSpanProcessor
from opentelemetry.sdk.trace.export import (
BatchSpanProcessor,
ConsoleSpanExporter,
SimpleSpanProcessor,
SpanExporter,
SpanExportResult,
)
from opentelemetry.trace import get_tracer_provider
from pydantic import __version__ as pydantic_version
from pytest import LogCaptureFixture
import logfire
import logfire._internal.config as config_module
from logfire import configure, propagate
from logfire._internal.baggage import DirectBaggageAttributesSpanProcessor
from logfire._internal.config import (
GLOBAL_CONFIG,
CodeSource,
ConsoleOptions,
LogfireConfig,
LogfireConfigWarning,
LogfireCredentials,
VariablesOptions,
get_base_url_from_token,
sanitize_project_name,
)
from logfire._internal.config_params import extract_list_of_str, normalize_token
from logfire._internal.exporters.console import (
ConsoleLogExporter,
ShowParentsConsoleSpanExporter,
SimpleConsoleSpanExporter,
)
from logfire._internal.exporters.dynamic_batch import DynamicBatchSpanProcessor
from logfire._internal.exporters.logs import CheckSuppressInstrumentationLogProcessorWrapper, MainLogProcessorWrapper
from logfire._internal.exporters.otlp import QuietLogExporter, QuietSpanExporter
from logfire._internal.exporters.processor_wrapper import (
CheckSuppressInstrumentationProcessorWrapper,
MainSpanProcessorWrapper,
)
from logfire._internal.exporters.quiet_metrics import QuietMetricExporter
from logfire._internal.exporters.remove_pending import RemovePendingSpansExporter
from logfire._internal.forwarding import OTLPForwardingManager
from logfire._internal.integrations.executors import deserialize_config, serialize_config
from logfire._internal.interactive import NonInteractiveError
from logfire._internal.tracer import PendingSpanProcessor
from logfire._internal.utils import SeededRandomIdGenerator, get_version
from logfire.exceptions import LogfireConfigError
from logfire.integrations.pydantic import get_pydantic_plugin_config
from logfire.propagate import NoExtractTraceContextPropagator, WarnOnExtractTraceContextPropagator
from logfire.testing import TestExporter, TestLogExporter
from logfire.version import VERSION
PROCESS_RUNTIME_VERSION_REGEX = r'(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)'
@pytest.fixture(autouse=True)
def no_log_on_config(config: None, caplog: pytest.LogCaptureFixture) -> None:
assert not caplog.messages

Xet Storage Details

Size:
156 kB
·
Xet hash:
55908d3f909717f3118562033c2211cb7ab77c1aec002619d5a1b0c7017dc2aa

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.