logfire-sdk 5.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- _logfire_sdk/logfire/.agents/skills/logfire-evals/SKILL.md +170 -0
- _logfire_sdk/logfire/.agents/skills/logfire-gateway/SKILL.md +156 -0
- _logfire_sdk/logfire/.agents/skills/logfire-infrastructure/SKILL.md +61 -0
- _logfire_sdk/logfire/.agents/skills/logfire-infrastructure/references/collector/host-and-infra-metrics.md +229 -0
- _logfire_sdk/logfire/.agents/skills/logfire-instrumentation/SKILL.md +292 -0
- _logfire_sdk/logfire/.agents/skills/logfire-instrumentation/references/auth.md +100 -0
- _logfire_sdk/logfire/.agents/skills/logfire-instrumentation/references/javascript/ai-sdk.md +145 -0
- _logfire_sdk/logfire/.agents/skills/logfire-instrumentation/references/javascript/cloudflare-and-deno.md +99 -0
- _logfire_sdk/logfire/.agents/skills/logfire-instrumentation/references/javascript/frameworks.md +22 -0
- _logfire_sdk/logfire/.agents/skills/logfire-instrumentation/references/javascript/installation-and-env.md +75 -0
- _logfire_sdk/logfire/.agents/skills/logfire-instrumentation/references/javascript/nextjs.md +78 -0
- _logfire_sdk/logfire/.agents/skills/logfire-instrumentation/references/javascript/node-runtime.md +132 -0
- _logfire_sdk/logfire/.agents/skills/logfire-instrumentation/references/javascript/patterns.md +184 -0
- _logfire_sdk/logfire/.agents/skills/logfire-instrumentation/references/javascript/project-detection.md +43 -0
- _logfire_sdk/logfire/.agents/skills/logfire-instrumentation/references/javascript/react-browser.md +18 -0
- _logfire_sdk/logfire/.agents/skills/logfire-instrumentation/references/javascript/verification-troubleshooting.md +68 -0
- _logfire_sdk/logfire/.agents/skills/logfire-instrumentation/references/python/integrations.md +104 -0
- _logfire_sdk/logfire/.agents/skills/logfire-instrumentation/references/python/logging-patterns.md +120 -0
- _logfire_sdk/logfire/.agents/skills/logfire-instrumentation/references/rust/patterns.md +113 -0
- _logfire_sdk/logfire/.agents/skills/logfire-setup/SKILL.md +58 -0
- _logfire_sdk/logfire/.agents/skills/logfire-setup-offline.md +715 -0
- _logfire_sdk/logfire/__init__.py +226 -0
- _logfire_sdk/logfire/__main__.py +6 -0
- _logfire_sdk/logfire/_internal/__init__.py +14 -0
- _logfire_sdk/logfire/_internal/ast_utils.py +264 -0
- _logfire_sdk/logfire/_internal/async_.py +125 -0
- _logfire_sdk/logfire/_internal/auth.py +298 -0
- _logfire_sdk/logfire/_internal/auto_trace/__init__.py +74 -0
- _logfire_sdk/logfire/_internal/auto_trace/import_hook.py +137 -0
- _logfire_sdk/logfire/_internal/auto_trace/rewrite_ast.py +185 -0
- _logfire_sdk/logfire/_internal/auto_trace/types.py +44 -0
- _logfire_sdk/logfire/_internal/baggage.py +109 -0
- _logfire_sdk/logfire/_internal/cli/__init__.py +1081 -0
- _logfire_sdk/logfire/_internal/cli/ai_tools.py +231 -0
- _logfire_sdk/logfire/_internal/cli/auth.py +151 -0
- _logfire_sdk/logfire/_internal/cli/gateway.py +627 -0
- _logfire_sdk/logfire/_internal/cli/gateway_auth.py +313 -0
- _logfire_sdk/logfire/_internal/cli/prompt.py +50 -0
- _logfire_sdk/logfire/_internal/cli/run.py +590 -0
- _logfire_sdk/logfire/_internal/client.py +178 -0
- _logfire_sdk/logfire/_internal/collect_system_info.py +29 -0
- _logfire_sdk/logfire/_internal/config.py +2471 -0
- _logfire_sdk/logfire/_internal/config_params.py +343 -0
- _logfire_sdk/logfire/_internal/constants.py +185 -0
- _logfire_sdk/logfire/_internal/db_statement_summary.py +140 -0
- _logfire_sdk/logfire/_internal/exporters/__init__.py +1 -0
- _logfire_sdk/logfire/_internal/exporters/console.py +517 -0
- _logfire_sdk/logfire/_internal/exporters/dynamic_batch.py +49 -0
- _logfire_sdk/logfire/_internal/exporters/logs.py +30 -0
- _logfire_sdk/logfire/_internal/exporters/otlp.py +517 -0
- _logfire_sdk/logfire/_internal/exporters/processor_wrapper.py +652 -0
- _logfire_sdk/logfire/_internal/exporters/quiet_metrics.py +18 -0
- _logfire_sdk/logfire/_internal/exporters/remove_pending.py +45 -0
- _logfire_sdk/logfire/_internal/exporters/test.py +257 -0
- _logfire_sdk/logfire/_internal/exporters/wrapper.py +106 -0
- _logfire_sdk/logfire/_internal/formatter.py +379 -0
- _logfire_sdk/logfire/_internal/forwarding.py +585 -0
- _logfire_sdk/logfire/_internal/http_transport.py +193 -0
- _logfire_sdk/logfire/_internal/instrument.py +254 -0
- _logfire_sdk/logfire/_internal/integrations/__init__.py +1 -0
- _logfire_sdk/logfire/_internal/integrations/aiohttp_client.py +324 -0
- _logfire_sdk/logfire/_internal/integrations/aiohttp_server.py +22 -0
- _logfire_sdk/logfire/_internal/integrations/asgi.py +117 -0
- _logfire_sdk/logfire/_internal/integrations/asyncpg.py +21 -0
- _logfire_sdk/logfire/_internal/integrations/aws_lambda.py +36 -0
- _logfire_sdk/logfire/_internal/integrations/celery.py +20 -0
- _logfire_sdk/logfire/_internal/integrations/claude_agent_sdk.py +628 -0
- _logfire_sdk/logfire/_internal/integrations/django.py +41 -0
- _logfire_sdk/logfire/_internal/integrations/dspy.py +20 -0
- _logfire_sdk/logfire/_internal/integrations/executors.py +99 -0
- _logfire_sdk/logfire/_internal/integrations/fastapi.py +421 -0
- _logfire_sdk/logfire/_internal/integrations/flask.py +53 -0
- _logfire_sdk/logfire/_internal/integrations/google_genai.py +66 -0
- _logfire_sdk/logfire/_internal/integrations/httpx.py +577 -0
- _logfire_sdk/logfire/_internal/integrations/litellm.py +20 -0
- _logfire_sdk/logfire/_internal/integrations/litestar.py +77 -0
- _logfire_sdk/logfire/_internal/integrations/llm_providers/anthropic.py +406 -0
- _logfire_sdk/logfire/_internal/integrations/llm_providers/llm_provider.py +251 -0
- _logfire_sdk/logfire/_internal/integrations/llm_providers/openai.py +892 -0
- _logfire_sdk/logfire/_internal/integrations/llm_providers/semconv.py +194 -0
- _logfire_sdk/logfire/_internal/integrations/llm_providers/types.py +36 -0
- _logfire_sdk/logfire/_internal/integrations/llm_providers/usage.py +89 -0
- _logfire_sdk/logfire/_internal/integrations/mcp.py +191 -0
- _logfire_sdk/logfire/_internal/integrations/monty.py +155 -0
- _logfire_sdk/logfire/_internal/integrations/mysql.py +34 -0
- _logfire_sdk/logfire/_internal/integrations/openai_agents.py +460 -0
- _logfire_sdk/logfire/_internal/integrations/print.py +176 -0
- _logfire_sdk/logfire/_internal/integrations/psycopg.py +126 -0
- _logfire_sdk/logfire/_internal/integrations/pydantic_ai.py +65 -0
- _logfire_sdk/logfire/_internal/integrations/pymongo.py +40 -0
- _logfire_sdk/logfire/_internal/integrations/pytest.py +648 -0
- _logfire_sdk/logfire/_internal/integrations/redis.py +57 -0
- _logfire_sdk/logfire/_internal/integrations/requests.py +34 -0
- _logfire_sdk/logfire/_internal/integrations/snowflake.py +162 -0
- _logfire_sdk/logfire/_internal/integrations/sqlalchemy.py +70 -0
- _logfire_sdk/logfire/_internal/integrations/sqlite3.py +29 -0
- _logfire_sdk/logfire/_internal/integrations/starlette.py +50 -0
- _logfire_sdk/logfire/_internal/integrations/surrealdb.py +137 -0
- _logfire_sdk/logfire/_internal/integrations/system_metrics.py +322 -0
- _logfire_sdk/logfire/_internal/integrations/wsgi.py +34 -0
- _logfire_sdk/logfire/_internal/interactive.py +115 -0
- _logfire_sdk/logfire/_internal/json_encoder.py +344 -0
- _logfire_sdk/logfire/_internal/json_formatter.py +350 -0
- _logfire_sdk/logfire/_internal/json_schema.py +455 -0
- _logfire_sdk/logfire/_internal/json_types.py +147 -0
- _logfire_sdk/logfire/_internal/logs.py +142 -0
- _logfire_sdk/logfire/_internal/main.py +3498 -0
- _logfire_sdk/logfire/_internal/metrics.py +283 -0
- _logfire_sdk/logfire/_internal/scrubbing.py +404 -0
- _logfire_sdk/logfire/_internal/server_response.py +44 -0
- _logfire_sdk/logfire/_internal/stack_info.py +147 -0
- _logfire_sdk/logfire/_internal/tracer.py +538 -0
- _logfire_sdk/logfire/_internal/ulid.py +40 -0
- _logfire_sdk/logfire/_internal/utils.py +550 -0
- _logfire_sdk/logfire/cli.py +3 -0
- _logfire_sdk/logfire/db_api.py +393 -0
- _logfire_sdk/logfire/exceptions.py +9 -0
- _logfire_sdk/logfire/experimental/__init__.py +0 -0
- _logfire_sdk/logfire/experimental/annotations.py +80 -0
- _logfire_sdk/logfire/experimental/api_client.py +1421 -0
- _logfire_sdk/logfire/integrations/__init__.py +4 -0
- _logfire_sdk/logfire/integrations/aiohttp_client.py +12 -0
- _logfire_sdk/logfire/integrations/flask.py +26 -0
- _logfire_sdk/logfire/integrations/httpx.py +49 -0
- _logfire_sdk/logfire/integrations/logging.py +153 -0
- _logfire_sdk/logfire/integrations/loguru.py +98 -0
- _logfire_sdk/logfire/integrations/psycopg.py +23 -0
- _logfire_sdk/logfire/integrations/pydantic.py +541 -0
- _logfire_sdk/logfire/integrations/redis.py +31 -0
- _logfire_sdk/logfire/integrations/sqlalchemy.py +12 -0
- _logfire_sdk/logfire/integrations/structlog.py +55 -0
- _logfire_sdk/logfire/integrations/wsgi.py +15 -0
- _logfire_sdk/logfire/propagate.py +161 -0
- _logfire_sdk/logfire/py.typed +0 -0
- _logfire_sdk/logfire/query_client.py +701 -0
- _logfire_sdk/logfire/sampling/__init__.py +9 -0
- _logfire_sdk/logfire/sampling/_tail_sampling.py +292 -0
- _logfire_sdk/logfire/testing.py +127 -0
- _logfire_sdk/logfire/types.py +303 -0
- _logfire_sdk/logfire/variables/__init__.py +154 -0
- _logfire_sdk/logfire/variables/_handlebars.py +77 -0
- _logfire_sdk/logfire/variables/abstract.py +2027 -0
- _logfire_sdk/logfire/variables/composition.py +430 -0
- _logfire_sdk/logfire/variables/config.py +694 -0
- _logfire_sdk/logfire/variables/local.py +134 -0
- _logfire_sdk/logfire/variables/remote.py +877 -0
- _logfire_sdk/logfire/variables/template_validation.py +208 -0
- _logfire_sdk/logfire/variables/variable.py +1299 -0
- _logfire_sdk/logfire/version.py +5 -0
- logfire/.agents/skills/logfire-evals/SKILL.md +170 -0
- logfire/.agents/skills/logfire-gateway/SKILL.md +156 -0
- logfire/.agents/skills/logfire-infrastructure/SKILL.md +61 -0
- logfire/.agents/skills/logfire-infrastructure/references/collector/host-and-infra-metrics.md +229 -0
- logfire/.agents/skills/logfire-instrumentation/SKILL.md +292 -0
- logfire/.agents/skills/logfire-instrumentation/references/auth.md +100 -0
- logfire/.agents/skills/logfire-instrumentation/references/javascript/ai-sdk.md +145 -0
- logfire/.agents/skills/logfire-instrumentation/references/javascript/cloudflare-and-deno.md +99 -0
- logfire/.agents/skills/logfire-instrumentation/references/javascript/frameworks.md +22 -0
- logfire/.agents/skills/logfire-instrumentation/references/javascript/installation-and-env.md +75 -0
- logfire/.agents/skills/logfire-instrumentation/references/javascript/nextjs.md +78 -0
- logfire/.agents/skills/logfire-instrumentation/references/javascript/node-runtime.md +132 -0
- logfire/.agents/skills/logfire-instrumentation/references/javascript/patterns.md +184 -0
- logfire/.agents/skills/logfire-instrumentation/references/javascript/project-detection.md +43 -0
- logfire/.agents/skills/logfire-instrumentation/references/javascript/react-browser.md +18 -0
- logfire/.agents/skills/logfire-instrumentation/references/javascript/verification-troubleshooting.md +68 -0
- logfire/.agents/skills/logfire-instrumentation/references/python/integrations.md +104 -0
- logfire/.agents/skills/logfire-instrumentation/references/python/logging-patterns.md +120 -0
- logfire/.agents/skills/logfire-instrumentation/references/rust/patterns.md +113 -0
- logfire/.agents/skills/logfire-setup/SKILL.md +58 -0
- logfire/.agents/skills/logfire-setup-offline.md +715 -0
- logfire/__init__.py +226 -0
- logfire/__main__.py +6 -0
- logfire/_internal/__init__.py +14 -0
- logfire/_internal/ast_utils.py +264 -0
- logfire/_internal/async_.py +125 -0
- logfire/_internal/auth.py +298 -0
- logfire/_internal/auto_trace/__init__.py +74 -0
- logfire/_internal/auto_trace/import_hook.py +137 -0
- logfire/_internal/auto_trace/rewrite_ast.py +185 -0
- logfire/_internal/auto_trace/types.py +44 -0
- logfire/_internal/baggage.py +109 -0
- logfire/_internal/cli/__init__.py +1081 -0
- logfire/_internal/cli/ai_tools.py +231 -0
- logfire/_internal/cli/auth.py +151 -0
- logfire/_internal/cli/gateway.py +627 -0
- logfire/_internal/cli/gateway_auth.py +313 -0
- logfire/_internal/cli/prompt.py +50 -0
- logfire/_internal/cli/run.py +590 -0
- logfire/_internal/client.py +178 -0
- logfire/_internal/collect_system_info.py +29 -0
- logfire/_internal/config.py +2471 -0
- logfire/_internal/config_params.py +343 -0
- logfire/_internal/constants.py +185 -0
- logfire/_internal/db_statement_summary.py +140 -0
- logfire/_internal/exporters/__init__.py +1 -0
- logfire/_internal/exporters/console.py +517 -0
- logfire/_internal/exporters/dynamic_batch.py +49 -0
- logfire/_internal/exporters/logs.py +30 -0
- logfire/_internal/exporters/otlp.py +517 -0
- logfire/_internal/exporters/processor_wrapper.py +652 -0
- logfire/_internal/exporters/quiet_metrics.py +18 -0
- logfire/_internal/exporters/remove_pending.py +45 -0
- logfire/_internal/exporters/test.py +257 -0
- logfire/_internal/exporters/wrapper.py +106 -0
- logfire/_internal/formatter.py +379 -0
- logfire/_internal/forwarding.py +585 -0
- logfire/_internal/http_transport.py +193 -0
- logfire/_internal/instrument.py +254 -0
- logfire/_internal/integrations/__init__.py +1 -0
- logfire/_internal/integrations/aiohttp_client.py +324 -0
- logfire/_internal/integrations/aiohttp_server.py +22 -0
- logfire/_internal/integrations/asgi.py +117 -0
- logfire/_internal/integrations/asyncpg.py +21 -0
- logfire/_internal/integrations/aws_lambda.py +36 -0
- logfire/_internal/integrations/celery.py +20 -0
- logfire/_internal/integrations/claude_agent_sdk.py +628 -0
- logfire/_internal/integrations/django.py +41 -0
- logfire/_internal/integrations/dspy.py +20 -0
- logfire/_internal/integrations/executors.py +99 -0
- logfire/_internal/integrations/fastapi.py +421 -0
- logfire/_internal/integrations/flask.py +53 -0
- logfire/_internal/integrations/google_genai.py +66 -0
- logfire/_internal/integrations/httpx.py +577 -0
- logfire/_internal/integrations/litellm.py +20 -0
- logfire/_internal/integrations/litestar.py +77 -0
- logfire/_internal/integrations/llm_providers/anthropic.py +406 -0
- logfire/_internal/integrations/llm_providers/llm_provider.py +251 -0
- logfire/_internal/integrations/llm_providers/openai.py +892 -0
- logfire/_internal/integrations/llm_providers/semconv.py +194 -0
- logfire/_internal/integrations/llm_providers/types.py +36 -0
- logfire/_internal/integrations/llm_providers/usage.py +89 -0
- logfire/_internal/integrations/mcp.py +191 -0
- logfire/_internal/integrations/monty.py +155 -0
- logfire/_internal/integrations/mysql.py +34 -0
- logfire/_internal/integrations/openai_agents.py +460 -0
- logfire/_internal/integrations/print.py +176 -0
- logfire/_internal/integrations/psycopg.py +126 -0
- logfire/_internal/integrations/pydantic_ai.py +65 -0
- logfire/_internal/integrations/pymongo.py +40 -0
- logfire/_internal/integrations/pytest.py +648 -0
- logfire/_internal/integrations/redis.py +57 -0
- logfire/_internal/integrations/requests.py +34 -0
- logfire/_internal/integrations/snowflake.py +162 -0
- logfire/_internal/integrations/sqlalchemy.py +70 -0
- logfire/_internal/integrations/sqlite3.py +29 -0
- logfire/_internal/integrations/starlette.py +50 -0
- logfire/_internal/integrations/surrealdb.py +137 -0
- logfire/_internal/integrations/system_metrics.py +322 -0
- logfire/_internal/integrations/wsgi.py +34 -0
- logfire/_internal/interactive.py +115 -0
- logfire/_internal/json_encoder.py +344 -0
- logfire/_internal/json_formatter.py +350 -0
- logfire/_internal/json_schema.py +455 -0
- logfire/_internal/json_types.py +147 -0
- logfire/_internal/logs.py +142 -0
- logfire/_internal/main.py +3498 -0
- logfire/_internal/metrics.py +283 -0
- logfire/_internal/scrubbing.py +404 -0
- logfire/_internal/server_response.py +44 -0
- logfire/_internal/stack_info.py +147 -0
- logfire/_internal/tracer.py +538 -0
- logfire/_internal/ulid.py +40 -0
- logfire/_internal/utils.py +550 -0
- logfire/cli.py +3 -0
- logfire/db_api.py +393 -0
- logfire/exceptions.py +9 -0
- logfire/experimental/__init__.py +0 -0
- logfire/experimental/annotations.py +80 -0
- logfire/experimental/api_client.py +1421 -0
- logfire/integrations/__init__.py +4 -0
- logfire/integrations/aiohttp_client.py +12 -0
- logfire/integrations/flask.py +26 -0
- logfire/integrations/httpx.py +49 -0
- logfire/integrations/logging.py +153 -0
- logfire/integrations/loguru.py +98 -0
- logfire/integrations/psycopg.py +23 -0
- logfire/integrations/pydantic.py +541 -0
- logfire/integrations/redis.py +31 -0
- logfire/integrations/sqlalchemy.py +12 -0
- logfire/integrations/structlog.py +55 -0
- logfire/integrations/wsgi.py +15 -0
- logfire/propagate.py +161 -0
- logfire/py.typed +0 -0
- logfire/query_client.py +701 -0
- logfire/sampling/__init__.py +9 -0
- logfire/sampling/_tail_sampling.py +292 -0
- logfire/testing.py +127 -0
- logfire/types.py +303 -0
- logfire/variables/__init__.py +154 -0
- logfire/variables/_handlebars.py +77 -0
- logfire/variables/abstract.py +2027 -0
- logfire/variables/composition.py +430 -0
- logfire/variables/config.py +694 -0
- logfire/variables/local.py +134 -0
- logfire/variables/remote.py +877 -0
- logfire/variables/template_validation.py +208 -0
- logfire/variables/variable.py +1299 -0
- logfire/version.py +5 -0
- logfire_sdk-5.3.0.dist-info/METADATA +140 -0
- logfire_sdk-5.3.0.dist-info/RECORD +304 -0
- logfire_sdk-5.3.0.dist-info/WHEEL +4 -0
- logfire_sdk-5.3.0.dist-info/entry_points.txt +6 -0
- logfire_sdk-5.3.0.dist-info/licenses/LICENSE +21 -0
- logfire_sdk.pth +2 -0
|
@@ -0,0 +1,3498 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
import inspect
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import sys
|
|
8
|
+
import warnings
|
|
9
|
+
from collections.abc import Iterable, Mapping, Sequence
|
|
10
|
+
from contextlib import AbstractContextManager
|
|
11
|
+
from contextvars import Token
|
|
12
|
+
from enum import Enum
|
|
13
|
+
from functools import cached_property, partial
|
|
14
|
+
from typing import ( # NOQA UP035
|
|
15
|
+
TYPE_CHECKING,
|
|
16
|
+
Any,
|
|
17
|
+
Callable,
|
|
18
|
+
Literal,
|
|
19
|
+
Type,
|
|
20
|
+
TypeVar,
|
|
21
|
+
cast,
|
|
22
|
+
overload,
|
|
23
|
+
)
|
|
24
|
+
from urllib.parse import quote
|
|
25
|
+
|
|
26
|
+
import opentelemetry.context as context_api
|
|
27
|
+
import opentelemetry.trace as trace_api
|
|
28
|
+
from opentelemetry.context import Context
|
|
29
|
+
from opentelemetry.metrics import CallbackT, Counter, Histogram, UpDownCounter
|
|
30
|
+
from opentelemetry.sdk.trace import ReadableSpan, Span
|
|
31
|
+
from opentelemetry.trace import SpanContext, SpanKind
|
|
32
|
+
from opentelemetry.util import types as otel_types
|
|
33
|
+
from typing_extensions import LiteralString, ParamSpec
|
|
34
|
+
|
|
35
|
+
from ..version import VERSION
|
|
36
|
+
from . import async_
|
|
37
|
+
from .auto_trace import AutoTraceModule, install_auto_tracing
|
|
38
|
+
from .config import GLOBAL_CONFIG, LogfireConfig
|
|
39
|
+
from .config_params import PydanticPluginRecordValues
|
|
40
|
+
from .constants import (
|
|
41
|
+
ATTRIBUTES_JSON_SCHEMA_KEY,
|
|
42
|
+
ATTRIBUTES_LOG_LEVEL_NUM_KEY,
|
|
43
|
+
ATTRIBUTES_MESSAGE_KEY,
|
|
44
|
+
ATTRIBUTES_MESSAGE_TEMPLATE_KEY,
|
|
45
|
+
ATTRIBUTES_SAMPLE_RATE_KEY,
|
|
46
|
+
ATTRIBUTES_SPAN_TYPE_KEY,
|
|
47
|
+
ATTRIBUTES_TAGS_KEY,
|
|
48
|
+
DISABLE_CONSOLE_KEY,
|
|
49
|
+
LEVEL_NUMBERS,
|
|
50
|
+
OTLP_MAX_INT_SIZE,
|
|
51
|
+
LevelName,
|
|
52
|
+
log_level_attributes,
|
|
53
|
+
)
|
|
54
|
+
from .formatter import logfire_format, logfire_format_with_magic
|
|
55
|
+
from .instrument import instrument
|
|
56
|
+
from .json_encoder import logfire_json_dumps
|
|
57
|
+
from .json_schema import (
|
|
58
|
+
JsonSchemaProperties,
|
|
59
|
+
attributes_json_schema,
|
|
60
|
+
attributes_json_schema_properties,
|
|
61
|
+
create_json_schema,
|
|
62
|
+
)
|
|
63
|
+
from .metrics import ProxyMeterProvider
|
|
64
|
+
from .stack_info import get_user_stack_info
|
|
65
|
+
from .tracer import (
|
|
66
|
+
ProxyTracerProvider,
|
|
67
|
+
_LogfireWrappedSpan, # pyright: ignore[reportPrivateUsage]
|
|
68
|
+
_ProxyTracer, # pyright: ignore[reportPrivateUsage]
|
|
69
|
+
set_exception_status,
|
|
70
|
+
)
|
|
71
|
+
from .utils import get_version, handle_internal_errors, log_internal_error, uniquify_sequence
|
|
72
|
+
|
|
73
|
+
if TYPE_CHECKING:
|
|
74
|
+
from types import ModuleType
|
|
75
|
+
from wsgiref.types import WSGIApplication
|
|
76
|
+
|
|
77
|
+
import anthropic
|
|
78
|
+
import httpx
|
|
79
|
+
import httpx2
|
|
80
|
+
import openai
|
|
81
|
+
import pydantic_ai.models
|
|
82
|
+
import requests
|
|
83
|
+
from anthropic.lib.bedrock import (
|
|
84
|
+
AnthropicBedrock as _AnthropicBedrock,
|
|
85
|
+
AsyncAnthropicBedrock as _AsyncAnthropicBedrock,
|
|
86
|
+
)
|
|
87
|
+
from django.http import HttpRequest, HttpResponse
|
|
88
|
+
from fastapi import FastAPI
|
|
89
|
+
from flask.app import Flask
|
|
90
|
+
from litestar import Litestar
|
|
91
|
+
from opentelemetry.instrumentation.asgi.types import ClientRequestHook, ClientResponseHook, ServerRequestHook
|
|
92
|
+
from opentelemetry.metrics import _Gauge as Gauge
|
|
93
|
+
from pydantic_evals.reporting import EvaluationReport
|
|
94
|
+
from pymongo.monitoring import CommandFailedEvent, CommandStartedEvent, CommandSucceededEvent
|
|
95
|
+
from snowflake.connector.connection import SnowflakeConnection
|
|
96
|
+
from sqlalchemy import Engine
|
|
97
|
+
from sqlalchemy.ext.asyncio import AsyncEngine
|
|
98
|
+
from starlette.applications import Starlette
|
|
99
|
+
from starlette.requests import Request
|
|
100
|
+
from starlette.responses import Response
|
|
101
|
+
from starlette.websockets import WebSocket
|
|
102
|
+
from surrealdb.connections.async_template import AsyncTemplate
|
|
103
|
+
from surrealdb.connections.sync_template import SyncTemplate
|
|
104
|
+
from typing_extensions import Unpack
|
|
105
|
+
|
|
106
|
+
from ..integrations.aiohttp_client import (
|
|
107
|
+
RequestHook as AiohttpClientRequestHook,
|
|
108
|
+
ResponseHook as AiohttpClientResponseHook,
|
|
109
|
+
)
|
|
110
|
+
from ..integrations.flask import (
|
|
111
|
+
CommenterOptions as FlaskCommenterOptions,
|
|
112
|
+
RequestHook as FlaskRequestHook,
|
|
113
|
+
ResponseHook as FlaskResponseHook,
|
|
114
|
+
)
|
|
115
|
+
from ..integrations.httpx import (
|
|
116
|
+
AsyncRequestHook as HttpxAsyncRequestHook,
|
|
117
|
+
AsyncResponseHook as HttpxAsyncResponseHook,
|
|
118
|
+
RequestHook as HttpxRequestHook,
|
|
119
|
+
ResponseHook as HttpxResponseHook,
|
|
120
|
+
)
|
|
121
|
+
from ..integrations.psycopg import CommenterOptions as PsycopgCommenterOptions
|
|
122
|
+
from ..integrations.redis import RequestHook as RedisRequestHook, ResponseHook as RedisResponseHook
|
|
123
|
+
from ..integrations.sqlalchemy import CommenterOptions as SQLAlchemyCommenterOptions
|
|
124
|
+
from ..integrations.wsgi import RequestHook as WSGIRequestHook, ResponseHook as WSGIResponseHook
|
|
125
|
+
from ..variables import (
|
|
126
|
+
ResolveFunction,
|
|
127
|
+
TemplateVariable,
|
|
128
|
+
ValidationReport,
|
|
129
|
+
Variable,
|
|
130
|
+
VariablesConfig,
|
|
131
|
+
)
|
|
132
|
+
from .config import TemplateMismatchPolicy
|
|
133
|
+
from .forwarding import ForwardExportRequestResponse
|
|
134
|
+
from .integrations.asgi import ASGIApp, ASGIInstrumentKwargs
|
|
135
|
+
from .integrations.aws_lambda import LambdaEvent, LambdaHandler
|
|
136
|
+
from .integrations.llm_providers.semconv import SemconvVersion
|
|
137
|
+
from .integrations.mysql import MySQLConnection
|
|
138
|
+
from .integrations.psycopg import Psycopg2Connection, PsycopgConnection
|
|
139
|
+
from .integrations.sqlite3 import SQLite3Connection
|
|
140
|
+
from .integrations.system_metrics import Base as SystemMetricsBase, Config as SystemMetricsConfig
|
|
141
|
+
from .utils import SysExcInfo
|
|
142
|
+
|
|
143
|
+
# This is the type of the exc_info/_exc_info parameter of the log methods.
|
|
144
|
+
# sys.exc_info() returns a tuple of (type, value, traceback) or (None, None, None).
|
|
145
|
+
# We just need the exception, but we allow the user to pass the tuple because:
|
|
146
|
+
# 1. It's convenient to pass the result of sys.exc_info() directly
|
|
147
|
+
# 2. It mirrors the exc_info argument of the stdlib logging methods
|
|
148
|
+
# 3. The argument name exc_info is very suggestive of the sys function.
|
|
149
|
+
ExcInfo = SysExcInfo | BaseException | bool | None
|
|
150
|
+
|
|
151
|
+
T = TypeVar('T')
|
|
152
|
+
InputsT = TypeVar('InputsT')
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class Logfire:
|
|
156
|
+
"""The main logfire class."""
|
|
157
|
+
|
|
158
|
+
def __init__(
|
|
159
|
+
self,
|
|
160
|
+
*,
|
|
161
|
+
config: LogfireConfig = GLOBAL_CONFIG,
|
|
162
|
+
sample_rate: float | None = None,
|
|
163
|
+
tags: Sequence[str] = (),
|
|
164
|
+
console_log: bool = True,
|
|
165
|
+
otel_scope: str = 'logfire',
|
|
166
|
+
) -> None:
|
|
167
|
+
self._tags = tuple(tags)
|
|
168
|
+
self._config = config
|
|
169
|
+
self._sample_rate = sample_rate
|
|
170
|
+
self._console_log = console_log
|
|
171
|
+
self._otel_scope = otel_scope
|
|
172
|
+
|
|
173
|
+
@property
|
|
174
|
+
def config(self) -> LogfireConfig:
|
|
175
|
+
return self._config
|
|
176
|
+
|
|
177
|
+
@property
|
|
178
|
+
def _variables(self) -> dict[str, Variable[Any] | TemplateVariable[Any, Any]]:
|
|
179
|
+
return self._config._variables # pyright: ignore[reportPrivateUsage]
|
|
180
|
+
|
|
181
|
+
@property
|
|
182
|
+
def resource_attributes(self) -> Mapping[str, Any]:
|
|
183
|
+
return self._tracer_provider.resource.attributes
|
|
184
|
+
|
|
185
|
+
@cached_property
|
|
186
|
+
def _tracer_provider(self) -> ProxyTracerProvider:
|
|
187
|
+
self._config.warn_if_not_initialized('No logs or spans will be created')
|
|
188
|
+
return self._config.get_tracer_provider()
|
|
189
|
+
|
|
190
|
+
@cached_property
|
|
191
|
+
def _meter_provider(self) -> ProxyMeterProvider: # pragma: no cover
|
|
192
|
+
return self._config.get_meter_provider()
|
|
193
|
+
|
|
194
|
+
@cached_property
|
|
195
|
+
def _meter(self):
|
|
196
|
+
return self._meter_provider.get_meter(self._otel_scope, VERSION)
|
|
197
|
+
|
|
198
|
+
@cached_property
|
|
199
|
+
def _logs_tracer(self) -> _ProxyTracer:
|
|
200
|
+
return self._get_tracer(is_span_tracer=False)
|
|
201
|
+
|
|
202
|
+
@cached_property
|
|
203
|
+
def _spans_tracer(self) -> _ProxyTracer:
|
|
204
|
+
return self._get_tracer(is_span_tracer=True)
|
|
205
|
+
|
|
206
|
+
def _get_tracer(self, *, is_span_tracer: bool) -> _ProxyTracer:
|
|
207
|
+
return self._tracer_provider.get_tracer(
|
|
208
|
+
self._otel_scope,
|
|
209
|
+
VERSION,
|
|
210
|
+
is_span_tracer=is_span_tracer,
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
# If any changes are made to this method, they may need to be reflected in `_fast_span` as well.
|
|
214
|
+
def _span(
|
|
215
|
+
self,
|
|
216
|
+
msg_template: str,
|
|
217
|
+
attributes: dict[str, Any],
|
|
218
|
+
*,
|
|
219
|
+
_tags: Sequence[str] | None = None,
|
|
220
|
+
_span_name: str | None = None,
|
|
221
|
+
_level: LevelName | int | None = None,
|
|
222
|
+
_links: Sequence[tuple[SpanContext, otel_types.Attributes]] = (),
|
|
223
|
+
_span_kind: SpanKind = SpanKind.INTERNAL,
|
|
224
|
+
) -> LogfireSpan:
|
|
225
|
+
try:
|
|
226
|
+
if _level is not None:
|
|
227
|
+
level_attributes = log_level_attributes(_level)
|
|
228
|
+
level_num = level_attributes[ATTRIBUTES_LOG_LEVEL_NUM_KEY]
|
|
229
|
+
if level_num < self.config.min_level:
|
|
230
|
+
return NoopSpan() # pyright: ignore[reportReturnType]
|
|
231
|
+
else:
|
|
232
|
+
level_attributes = None
|
|
233
|
+
|
|
234
|
+
stack_info = get_user_stack_info()
|
|
235
|
+
merged_attributes = {**stack_info, **attributes}
|
|
236
|
+
|
|
237
|
+
if self._config.inspect_arguments:
|
|
238
|
+
fstring_frame = inspect.currentframe().f_back # pyright: ignore[reportOptionalMemberAccess]
|
|
239
|
+
else:
|
|
240
|
+
fstring_frame = None
|
|
241
|
+
|
|
242
|
+
log_message, extra_attrs, msg_template = logfire_format_with_magic(
|
|
243
|
+
msg_template,
|
|
244
|
+
merged_attributes,
|
|
245
|
+
self._config.scrubber,
|
|
246
|
+
fstring_frame=fstring_frame,
|
|
247
|
+
)
|
|
248
|
+
merged_attributes.update(extra_attrs)
|
|
249
|
+
attributes.update(extra_attrs) # for the JSON schema
|
|
250
|
+
merged_attributes[ATTRIBUTES_MESSAGE_TEMPLATE_KEY] = msg_template
|
|
251
|
+
merged_attributes[ATTRIBUTES_MESSAGE_KEY] = log_message
|
|
252
|
+
|
|
253
|
+
otlp_attributes = prepare_otlp_attributes(merged_attributes)
|
|
254
|
+
|
|
255
|
+
if json_schema_properties := attributes_json_schema_properties(attributes):
|
|
256
|
+
otlp_attributes[ATTRIBUTES_JSON_SCHEMA_KEY] = attributes_json_schema(json_schema_properties)
|
|
257
|
+
|
|
258
|
+
tags = (self._tags or ()) + tuple(_tags or ())
|
|
259
|
+
if tags:
|
|
260
|
+
otlp_attributes[ATTRIBUTES_TAGS_KEY] = uniquify_sequence(tags)
|
|
261
|
+
|
|
262
|
+
sample_rate = (
|
|
263
|
+
self._sample_rate
|
|
264
|
+
if self._sample_rate is not None
|
|
265
|
+
else otlp_attributes.pop(ATTRIBUTES_SAMPLE_RATE_KEY, None)
|
|
266
|
+
)
|
|
267
|
+
if sample_rate is not None and sample_rate != 1: # pragma: no cover
|
|
268
|
+
otlp_attributes[ATTRIBUTES_SAMPLE_RATE_KEY] = sample_rate
|
|
269
|
+
|
|
270
|
+
if level_attributes is not None:
|
|
271
|
+
otlp_attributes.update(level_attributes)
|
|
272
|
+
|
|
273
|
+
return LogfireSpan(
|
|
274
|
+
_span_name or msg_template,
|
|
275
|
+
otlp_attributes,
|
|
276
|
+
self._spans_tracer,
|
|
277
|
+
json_schema_properties,
|
|
278
|
+
links=_links,
|
|
279
|
+
span_kind=_span_kind,
|
|
280
|
+
)
|
|
281
|
+
except Exception:
|
|
282
|
+
log_internal_error()
|
|
283
|
+
return NoopSpan() # pyright: ignore[reportReturnType]
|
|
284
|
+
|
|
285
|
+
def _fast_span(self, name: str, attributes: otel_types.Attributes, **kwargs: Any) -> FastLogfireSpan:
|
|
286
|
+
"""A simple version of `_span` optimized for auto-tracing that doesn't support message formatting.
|
|
287
|
+
|
|
288
|
+
Returns a similarly simplified version of `LogfireSpan` which must immediately be used as a context manager.
|
|
289
|
+
"""
|
|
290
|
+
try:
|
|
291
|
+
span = self._spans_tracer.start_span(name=name, attributes=attributes, **kwargs)
|
|
292
|
+
return FastLogfireSpan(span)
|
|
293
|
+
except Exception: # pragma: no cover
|
|
294
|
+
log_internal_error()
|
|
295
|
+
return NoopSpan() # pyright: ignore[reportReturnType]
|
|
296
|
+
|
|
297
|
+
def _instrument_span_with_args(
|
|
298
|
+
self, name: str, attributes: dict[str, otel_types.AttributeValue], function_args: dict[str, Any], **kwargs: Any
|
|
299
|
+
) -> FastLogfireSpan:
|
|
300
|
+
"""A version of `_span` used by `@instrument` with `extract_args=True`.
|
|
301
|
+
|
|
302
|
+
This is a bit faster than `_span` but not as fast as `_fast_span` because it supports message formatting
|
|
303
|
+
and arbitrary types of attributes.
|
|
304
|
+
"""
|
|
305
|
+
try:
|
|
306
|
+
attributes = attributes.copy()
|
|
307
|
+
msg_template: str = attributes[ATTRIBUTES_MESSAGE_TEMPLATE_KEY] # pyright: ignore[reportAssignmentType]
|
|
308
|
+
attributes[ATTRIBUTES_MESSAGE_KEY] = logfire_format(msg_template, function_args, self._config.scrubber)
|
|
309
|
+
if json_schema_properties := attributes_json_schema_properties(function_args): # pragma: no branch
|
|
310
|
+
attributes[ATTRIBUTES_JSON_SCHEMA_KEY] = attributes_json_schema(json_schema_properties)
|
|
311
|
+
attributes.update(prepare_otlp_attributes(function_args))
|
|
312
|
+
return self._fast_span(name, attributes, **kwargs)
|
|
313
|
+
except Exception: # pragma: no cover
|
|
314
|
+
log_internal_error()
|
|
315
|
+
return NoopSpan() # pyright: ignore[reportReturnType]
|
|
316
|
+
|
|
317
|
+
def trace(
|
|
318
|
+
self,
|
|
319
|
+
msg_template: str,
|
|
320
|
+
/,
|
|
321
|
+
*,
|
|
322
|
+
_tags: Sequence[str] | None = None,
|
|
323
|
+
_exc_info: ExcInfo = False,
|
|
324
|
+
**attributes: Any,
|
|
325
|
+
) -> None:
|
|
326
|
+
"""Log a trace message.
|
|
327
|
+
|
|
328
|
+
```py
|
|
329
|
+
import logfire
|
|
330
|
+
|
|
331
|
+
logfire.configure()
|
|
332
|
+
|
|
333
|
+
logfire.trace('This is a trace log')
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
Args:
|
|
337
|
+
msg_template: The message to log.
|
|
338
|
+
attributes: The attributes to bind to the log.
|
|
339
|
+
_tags: An optional sequence of tags to include in the log.
|
|
340
|
+
_exc_info: Set to an exception or a tuple as returned by [`sys.exc_info()`][sys.exc_info]
|
|
341
|
+
to record a traceback with the log message.
|
|
342
|
+
|
|
343
|
+
Set to `True` to use the currently handled exception.
|
|
344
|
+
"""
|
|
345
|
+
if any(k.startswith('_') for k in attributes):
|
|
346
|
+
raise ValueError('Attribute keys cannot start with an underscore.')
|
|
347
|
+
self.log('trace', msg_template, attributes, tags=_tags, exc_info=_exc_info)
|
|
348
|
+
|
|
349
|
+
def debug(
|
|
350
|
+
self,
|
|
351
|
+
msg_template: str,
|
|
352
|
+
/,
|
|
353
|
+
*,
|
|
354
|
+
_tags: Sequence[str] | None = None,
|
|
355
|
+
_exc_info: ExcInfo = False,
|
|
356
|
+
**attributes: Any,
|
|
357
|
+
) -> None:
|
|
358
|
+
"""Log a debug message.
|
|
359
|
+
|
|
360
|
+
```py
|
|
361
|
+
import logfire
|
|
362
|
+
|
|
363
|
+
logfire.configure()
|
|
364
|
+
|
|
365
|
+
logfire.debug('This is a debug log')
|
|
366
|
+
```
|
|
367
|
+
|
|
368
|
+
Args:
|
|
369
|
+
msg_template: The message to log.
|
|
370
|
+
attributes: The attributes to bind to the log.
|
|
371
|
+
_tags: An optional sequence of tags to include in the log.
|
|
372
|
+
_exc_info: Set to an exception or a tuple as returned by [`sys.exc_info()`][sys.exc_info]
|
|
373
|
+
to record a traceback with the log message.
|
|
374
|
+
|
|
375
|
+
Set to `True` to use the currently handled exception.
|
|
376
|
+
"""
|
|
377
|
+
if any(k.startswith('_') for k in attributes):
|
|
378
|
+
raise ValueError('Attribute keys cannot start with an underscore.')
|
|
379
|
+
self.log('debug', msg_template, attributes, tags=_tags, exc_info=_exc_info)
|
|
380
|
+
|
|
381
|
+
def info(
|
|
382
|
+
self,
|
|
383
|
+
msg_template: str,
|
|
384
|
+
/,
|
|
385
|
+
*,
|
|
386
|
+
_tags: Sequence[str] | None = None,
|
|
387
|
+
_exc_info: ExcInfo = False,
|
|
388
|
+
**attributes: Any,
|
|
389
|
+
) -> None:
|
|
390
|
+
"""Log an info message.
|
|
391
|
+
|
|
392
|
+
```py
|
|
393
|
+
import logfire
|
|
394
|
+
|
|
395
|
+
logfire.configure()
|
|
396
|
+
|
|
397
|
+
logfire.info('This is an info log')
|
|
398
|
+
```
|
|
399
|
+
|
|
400
|
+
Args:
|
|
401
|
+
msg_template: The message to log.
|
|
402
|
+
attributes: The attributes to bind to the log.
|
|
403
|
+
_tags: An optional sequence of tags to include in the log.
|
|
404
|
+
_exc_info: Set to an exception or a tuple as returned by [`sys.exc_info()`][sys.exc_info]
|
|
405
|
+
to record a traceback with the log message.
|
|
406
|
+
|
|
407
|
+
Set to `True` to use the currently handled exception.
|
|
408
|
+
"""
|
|
409
|
+
if any(k.startswith('_') for k in attributes):
|
|
410
|
+
raise ValueError('Attribute keys cannot start with an underscore.')
|
|
411
|
+
self.log('info', msg_template, attributes, tags=_tags, exc_info=_exc_info)
|
|
412
|
+
|
|
413
|
+
def notice(
|
|
414
|
+
self,
|
|
415
|
+
msg_template: str,
|
|
416
|
+
/,
|
|
417
|
+
*,
|
|
418
|
+
_tags: Sequence[str] | None = None,
|
|
419
|
+
_exc_info: ExcInfo = False,
|
|
420
|
+
**attributes: Any,
|
|
421
|
+
) -> None:
|
|
422
|
+
"""Log a notice message.
|
|
423
|
+
|
|
424
|
+
```py
|
|
425
|
+
import logfire
|
|
426
|
+
|
|
427
|
+
logfire.configure()
|
|
428
|
+
|
|
429
|
+
logfire.notice('This is a notice log')
|
|
430
|
+
```
|
|
431
|
+
|
|
432
|
+
Args:
|
|
433
|
+
msg_template: The message to log.
|
|
434
|
+
attributes: The attributes to bind to the log.
|
|
435
|
+
_tags: An optional sequence of tags to include in the log.
|
|
436
|
+
_exc_info: Set to an exception or a tuple as returned by [`sys.exc_info()`][sys.exc_info]
|
|
437
|
+
to record a traceback with the log message.
|
|
438
|
+
|
|
439
|
+
Set to `True` to use the currently handled exception.
|
|
440
|
+
"""
|
|
441
|
+
if any(k.startswith('_') for k in attributes):
|
|
442
|
+
raise ValueError('Attribute keys cannot start with an underscore.')
|
|
443
|
+
self.log('notice', msg_template, attributes, tags=_tags, exc_info=_exc_info)
|
|
444
|
+
|
|
445
|
+
def warning(
|
|
446
|
+
self,
|
|
447
|
+
msg_template: str,
|
|
448
|
+
/,
|
|
449
|
+
*,
|
|
450
|
+
_tags: Sequence[str] | None = None,
|
|
451
|
+
_exc_info: ExcInfo = False,
|
|
452
|
+
**attributes: Any,
|
|
453
|
+
) -> None:
|
|
454
|
+
"""Log a warning message.
|
|
455
|
+
|
|
456
|
+
```py
|
|
457
|
+
import logfire
|
|
458
|
+
|
|
459
|
+
logfire.configure()
|
|
460
|
+
|
|
461
|
+
logfire.warning('This is a warning log')
|
|
462
|
+
```
|
|
463
|
+
|
|
464
|
+
`logfire.warn` is an alias of `logfire.warning`.
|
|
465
|
+
|
|
466
|
+
Args:
|
|
467
|
+
msg_template: The message to log.
|
|
468
|
+
attributes: The attributes to bind to the log.
|
|
469
|
+
_tags: An optional sequence of tags to include in the log.
|
|
470
|
+
_exc_info: Set to an exception or a tuple as returned by [`sys.exc_info()`][sys.exc_info]
|
|
471
|
+
to record a traceback with the log message.
|
|
472
|
+
|
|
473
|
+
Set to `True` to use the currently handled exception.
|
|
474
|
+
"""
|
|
475
|
+
if any(k.startswith('_') for k in attributes):
|
|
476
|
+
raise ValueError('Attribute keys cannot start with an underscore.')
|
|
477
|
+
self.log('warn', msg_template, attributes, tags=_tags, exc_info=_exc_info)
|
|
478
|
+
|
|
479
|
+
warn = warning
|
|
480
|
+
|
|
481
|
+
def error(
|
|
482
|
+
self,
|
|
483
|
+
msg_template: str,
|
|
484
|
+
/,
|
|
485
|
+
*,
|
|
486
|
+
_tags: Sequence[str] | None = None,
|
|
487
|
+
_exc_info: ExcInfo = False,
|
|
488
|
+
**attributes: Any,
|
|
489
|
+
) -> None:
|
|
490
|
+
"""Log an error message.
|
|
491
|
+
|
|
492
|
+
```py
|
|
493
|
+
import logfire
|
|
494
|
+
|
|
495
|
+
logfire.configure()
|
|
496
|
+
|
|
497
|
+
logfire.error('This is an error log')
|
|
498
|
+
```
|
|
499
|
+
|
|
500
|
+
Args:
|
|
501
|
+
msg_template: The message to log.
|
|
502
|
+
attributes: The attributes to bind to the log.
|
|
503
|
+
_tags: An optional sequence of tags to include in the log.
|
|
504
|
+
_exc_info: Set to an exception or a tuple as returned by [`sys.exc_info()`][sys.exc_info]
|
|
505
|
+
to record a traceback with the log message.
|
|
506
|
+
|
|
507
|
+
Set to `True` to use the currently handled exception.
|
|
508
|
+
"""
|
|
509
|
+
if any(k.startswith('_') for k in attributes):
|
|
510
|
+
raise ValueError('Attribute keys cannot start with an underscore.')
|
|
511
|
+
self.log('error', msg_template, attributes, tags=_tags, exc_info=_exc_info)
|
|
512
|
+
|
|
513
|
+
def fatal(
|
|
514
|
+
self,
|
|
515
|
+
msg_template: str,
|
|
516
|
+
/,
|
|
517
|
+
*,
|
|
518
|
+
_tags: Sequence[str] | None = None,
|
|
519
|
+
_exc_info: ExcInfo = False,
|
|
520
|
+
**attributes: Any,
|
|
521
|
+
) -> None:
|
|
522
|
+
"""Log a fatal message.
|
|
523
|
+
|
|
524
|
+
```py
|
|
525
|
+
import logfire
|
|
526
|
+
|
|
527
|
+
logfire.configure()
|
|
528
|
+
|
|
529
|
+
logfire.fatal('This is a fatal log')
|
|
530
|
+
```
|
|
531
|
+
|
|
532
|
+
Args:
|
|
533
|
+
msg_template: The message to log.
|
|
534
|
+
attributes: The attributes to bind to the log.
|
|
535
|
+
_tags: An optional sequence of tags to include in the log.
|
|
536
|
+
_exc_info: Set to an exception or a tuple as returned by [`sys.exc_info()`][sys.exc_info]
|
|
537
|
+
to record a traceback with the log message.
|
|
538
|
+
|
|
539
|
+
Set to `True` to use the currently handled exception.
|
|
540
|
+
"""
|
|
541
|
+
if any(k.startswith('_') for k in attributes):
|
|
542
|
+
raise ValueError('Attribute keys cannot start with an underscore.')
|
|
543
|
+
self.log('fatal', msg_template, attributes, tags=_tags, exc_info=_exc_info)
|
|
544
|
+
|
|
545
|
+
def exception(
|
|
546
|
+
self,
|
|
547
|
+
msg_template: str,
|
|
548
|
+
/,
|
|
549
|
+
*,
|
|
550
|
+
_tags: Sequence[str] | None = None,
|
|
551
|
+
_exc_info: ExcInfo = True,
|
|
552
|
+
**attributes: Any,
|
|
553
|
+
) -> None:
|
|
554
|
+
"""The same as `error` but with `_exc_info=True` by default.
|
|
555
|
+
|
|
556
|
+
This means that a traceback will be logged for any currently handled exception.
|
|
557
|
+
|
|
558
|
+
Args:
|
|
559
|
+
msg_template: The message to log.
|
|
560
|
+
attributes: The attributes to bind to the log.
|
|
561
|
+
_tags: An optional sequence of tags to include in the log.
|
|
562
|
+
_exc_info: Set to an exception or a tuple as returned by [`sys.exc_info()`][sys.exc_info]
|
|
563
|
+
to record a traceback with the log message.
|
|
564
|
+
"""
|
|
565
|
+
if any(k.startswith('_') for k in attributes): # pragma: no cover
|
|
566
|
+
raise ValueError('Attribute keys cannot start with an underscore.')
|
|
567
|
+
self.log('error', msg_template, attributes, tags=_tags, exc_info=_exc_info)
|
|
568
|
+
|
|
569
|
+
def span(
|
|
570
|
+
self,
|
|
571
|
+
msg_template: str,
|
|
572
|
+
/,
|
|
573
|
+
*,
|
|
574
|
+
_tags: Sequence[str] | None = None,
|
|
575
|
+
_span_name: str | None = None,
|
|
576
|
+
_level: LevelName | None = None,
|
|
577
|
+
_links: Sequence[tuple[SpanContext, otel_types.Attributes]] = (),
|
|
578
|
+
_span_kind: SpanKind = SpanKind.INTERNAL,
|
|
579
|
+
**attributes: Any,
|
|
580
|
+
) -> LogfireSpan:
|
|
581
|
+
"""Context manager for creating a span.
|
|
582
|
+
|
|
583
|
+
```py
|
|
584
|
+
import logfire
|
|
585
|
+
|
|
586
|
+
logfire.configure()
|
|
587
|
+
|
|
588
|
+
with logfire.span('This is a span {a=}', a='data'):
|
|
589
|
+
logfire.info('new log 1')
|
|
590
|
+
```
|
|
591
|
+
|
|
592
|
+
Args:
|
|
593
|
+
msg_template: The template for the span message.
|
|
594
|
+
_span_name: The span name. If not provided, the `msg_template` will be used.
|
|
595
|
+
_tags: An optional sequence of tags to include in the span.
|
|
596
|
+
_level: An optional log level name.
|
|
597
|
+
_links: An optional sequence of links to other spans. Each link is a tuple of a span context and attributes.
|
|
598
|
+
_span_kind: The [OpenTelemetry span kind](https://opentelemetry.io/docs/concepts/signals/traces/#span-kind).
|
|
599
|
+
If not provided, defaults to `INTERNAL`.
|
|
600
|
+
Users don't typically need to set this.
|
|
601
|
+
Not related to the `kind` column of the `records` table in Logfire.
|
|
602
|
+
attributes: The arguments to include in the span and format the message template with.
|
|
603
|
+
Attributes starting with an underscore are not allowed.
|
|
604
|
+
"""
|
|
605
|
+
if any(k.startswith('_') for k in attributes):
|
|
606
|
+
raise ValueError('Attribute keys cannot start with an underscore.')
|
|
607
|
+
return self._span(
|
|
608
|
+
msg_template,
|
|
609
|
+
attributes,
|
|
610
|
+
_tags=_tags,
|
|
611
|
+
_span_name=_span_name,
|
|
612
|
+
_level=_level,
|
|
613
|
+
_links=_links,
|
|
614
|
+
_span_kind=_span_kind,
|
|
615
|
+
)
|
|
616
|
+
|
|
617
|
+
@overload
|
|
618
|
+
def instrument(
|
|
619
|
+
self,
|
|
620
|
+
msg_template: LiteralString | None = None,
|
|
621
|
+
*,
|
|
622
|
+
span_name: str | None = None,
|
|
623
|
+
extract_args: bool | Iterable[str] = True,
|
|
624
|
+
record_return: bool = False,
|
|
625
|
+
allow_generator: bool = False,
|
|
626
|
+
new_trace: bool = False,
|
|
627
|
+
level: LevelName | int | None = None,
|
|
628
|
+
) -> Callable[[Callable[P, R]], Callable[P, R]]:
|
|
629
|
+
"""Decorator for instrumenting a function as a span.
|
|
630
|
+
|
|
631
|
+
```py
|
|
632
|
+
import logfire
|
|
633
|
+
|
|
634
|
+
logfire.configure()
|
|
635
|
+
|
|
636
|
+
|
|
637
|
+
@logfire.instrument('This is a span {a=}')
|
|
638
|
+
def my_function(a: int):
|
|
639
|
+
logfire.info('new log {a=}', a=a)
|
|
640
|
+
```
|
|
641
|
+
|
|
642
|
+
Args:
|
|
643
|
+
msg_template: The template for the span message. If not provided, the module and function name will be used.
|
|
644
|
+
span_name: The span name. If not provided, the `msg_template` will be used.
|
|
645
|
+
extract_args: By default, all function call arguments are logged as span attributes.
|
|
646
|
+
Set to `False` to disable this, or pass an iterable of argument names to include.
|
|
647
|
+
record_return: Set to `True` to record the return value of the function as an attribute.
|
|
648
|
+
Ignored for generators.
|
|
649
|
+
allow_generator: Set to `True` to prevent a warning when instrumenting a generator function.
|
|
650
|
+
Read https://logfire.pydantic.dev/docs/guides/advanced/generators/#using-logfireinstrument first.
|
|
651
|
+
new_trace: Set to `True` to start a new trace with a span link to the current span
|
|
652
|
+
instead of creating a child of the current span.
|
|
653
|
+
level: The log level for the span. If provided, the span will be tagged with this level
|
|
654
|
+
and suppressed if the level is below the configured `min_level`.
|
|
655
|
+
"""
|
|
656
|
+
|
|
657
|
+
@overload
|
|
658
|
+
def instrument(self, func: Callable[P, R]) -> Callable[P, R]:
|
|
659
|
+
"""Decorator for instrumenting a function as a span, with default configuration.
|
|
660
|
+
|
|
661
|
+
```py
|
|
662
|
+
import logfire
|
|
663
|
+
|
|
664
|
+
logfire.configure()
|
|
665
|
+
|
|
666
|
+
|
|
667
|
+
@logfire.instrument
|
|
668
|
+
def my_function(a: int):
|
|
669
|
+
logfire.info('new log {a=}', a=a)
|
|
670
|
+
```
|
|
671
|
+
"""
|
|
672
|
+
|
|
673
|
+
def instrument( # pyright: ignore[reportInconsistentOverload]
|
|
674
|
+
self,
|
|
675
|
+
msg_template: Callable[P, R] | LiteralString | None = None,
|
|
676
|
+
*,
|
|
677
|
+
span_name: str | None = None,
|
|
678
|
+
extract_args: bool | Iterable[str] = True,
|
|
679
|
+
record_return: bool = False,
|
|
680
|
+
allow_generator: bool = False,
|
|
681
|
+
new_trace: bool = False,
|
|
682
|
+
level: LevelName | int | None = None,
|
|
683
|
+
) -> Callable[[Callable[P, R]], Callable[P, R]] | Callable[P, R]:
|
|
684
|
+
"""Decorator for instrumenting a function as a span.
|
|
685
|
+
|
|
686
|
+
```py
|
|
687
|
+
import logfire
|
|
688
|
+
|
|
689
|
+
logfire.configure()
|
|
690
|
+
|
|
691
|
+
|
|
692
|
+
@logfire.instrument('This is a span {a=}')
|
|
693
|
+
def my_function(a: int):
|
|
694
|
+
logfire.info('new log {a=}', a=a)
|
|
695
|
+
```
|
|
696
|
+
|
|
697
|
+
Args:
|
|
698
|
+
msg_template: The template for the span message. If not provided, the module and function name will be used.
|
|
699
|
+
span_name: The span name. If not provided, the `msg_template` will be used.
|
|
700
|
+
extract_args: By default, all function call arguments are logged as span attributes.
|
|
701
|
+
Set to `False` to disable this, or pass an iterable of argument names to include.
|
|
702
|
+
record_return: Set to `True` to record the return value of the function as an attribute.
|
|
703
|
+
Ignored for generators.
|
|
704
|
+
allow_generator: Set to `True` to prevent a warning when instrumenting a generator function.
|
|
705
|
+
Read https://logfire.pydantic.dev/docs/guides/advanced/generators/#using-logfireinstrument first.
|
|
706
|
+
new_trace: Set to `True` to start a new trace with a span link to the current span
|
|
707
|
+
instead of creating a child of the current span.
|
|
708
|
+
level: The log level for the span. If provided, the span will be tagged with this level
|
|
709
|
+
and suppressed if the level is below the configured `min_level`.
|
|
710
|
+
"""
|
|
711
|
+
if callable(msg_template):
|
|
712
|
+
return self.instrument()(msg_template)
|
|
713
|
+
return instrument(
|
|
714
|
+
self,
|
|
715
|
+
tuple(self._tags),
|
|
716
|
+
msg_template,
|
|
717
|
+
span_name,
|
|
718
|
+
extract_args,
|
|
719
|
+
record_return,
|
|
720
|
+
allow_generator,
|
|
721
|
+
new_trace,
|
|
722
|
+
level=level,
|
|
723
|
+
)
|
|
724
|
+
|
|
725
|
+
def log(
|
|
726
|
+
self,
|
|
727
|
+
level: LevelName | int,
|
|
728
|
+
msg_template: str,
|
|
729
|
+
attributes: dict[str, Any] | None = None,
|
|
730
|
+
tags: Sequence[str] | None = None,
|
|
731
|
+
exc_info: ExcInfo = False,
|
|
732
|
+
console_log: bool | None = None,
|
|
733
|
+
) -> None:
|
|
734
|
+
"""Log a message.
|
|
735
|
+
|
|
736
|
+
```py
|
|
737
|
+
import logfire
|
|
738
|
+
|
|
739
|
+
logfire.configure()
|
|
740
|
+
|
|
741
|
+
logfire.log('info', 'This is a log {a}', {'a': 'Apple'})
|
|
742
|
+
```
|
|
743
|
+
|
|
744
|
+
Args:
|
|
745
|
+
level: The level of the log.
|
|
746
|
+
msg_template: The message to log.
|
|
747
|
+
attributes: The attributes to bind to the log.
|
|
748
|
+
tags: An optional sequence of tags to include in the log.
|
|
749
|
+
exc_info: Set to an exception or a tuple as returned by [`sys.exc_info()`][sys.exc_info]
|
|
750
|
+
to record a traceback with the log message.
|
|
751
|
+
|
|
752
|
+
Set to `True` to use the currently handled exception.
|
|
753
|
+
console_log: Whether to log to the console, defaults to `True`.
|
|
754
|
+
"""
|
|
755
|
+
with handle_internal_errors:
|
|
756
|
+
level_attributes = log_level_attributes(level)
|
|
757
|
+
level_num = level_attributes[ATTRIBUTES_LOG_LEVEL_NUM_KEY]
|
|
758
|
+
if level_num < self.config.min_level:
|
|
759
|
+
return
|
|
760
|
+
|
|
761
|
+
stack_info = get_user_stack_info()
|
|
762
|
+
|
|
763
|
+
attributes = attributes or {}
|
|
764
|
+
merged_attributes = {**stack_info, **attributes}
|
|
765
|
+
if (msg := attributes.pop(ATTRIBUTES_MESSAGE_KEY, None)) is None:
|
|
766
|
+
fstring_frame = None
|
|
767
|
+
if self._config.inspect_arguments:
|
|
768
|
+
fstring_frame = inspect.currentframe()
|
|
769
|
+
if fstring_frame.f_back.f_code.co_filename == Logfire.log.__code__.co_filename: # pyright: ignore[reportOptionalMemberAccess]
|
|
770
|
+
# fstring_frame.f_back should be the user's frame.
|
|
771
|
+
# The user called logfire.info or a similar method rather than calling logfire.log directly.
|
|
772
|
+
fstring_frame = fstring_frame.f_back # pyright: ignore[reportOptionalMemberAccess]
|
|
773
|
+
|
|
774
|
+
msg, extra_attrs, msg_template = logfire_format_with_magic(
|
|
775
|
+
msg_template,
|
|
776
|
+
merged_attributes,
|
|
777
|
+
self._config.scrubber,
|
|
778
|
+
fstring_frame=fstring_frame,
|
|
779
|
+
)
|
|
780
|
+
if extra_attrs:
|
|
781
|
+
merged_attributes.update(extra_attrs)
|
|
782
|
+
# Only do this if extra_attrs is not empty since the copy of `attributes` might be expensive.
|
|
783
|
+
# We update both because attributes_json_schema_properties looks at `attributes`.
|
|
784
|
+
attributes = {**attributes, **extra_attrs}
|
|
785
|
+
else:
|
|
786
|
+
# The message has already been filled in, presumably by a logging integration.
|
|
787
|
+
# Make sure it's a string.
|
|
788
|
+
msg = merged_attributes[ATTRIBUTES_MESSAGE_KEY] = str(msg)
|
|
789
|
+
msg_template = str(msg_template)
|
|
790
|
+
|
|
791
|
+
otlp_attributes = prepare_otlp_attributes(merged_attributes)
|
|
792
|
+
otlp_attributes = {
|
|
793
|
+
ATTRIBUTES_SPAN_TYPE_KEY: 'log',
|
|
794
|
+
**level_attributes,
|
|
795
|
+
ATTRIBUTES_MESSAGE_TEMPLATE_KEY: msg_template,
|
|
796
|
+
ATTRIBUTES_MESSAGE_KEY: msg,
|
|
797
|
+
**otlp_attributes,
|
|
798
|
+
}
|
|
799
|
+
if json_schema_properties := attributes_json_schema_properties(attributes):
|
|
800
|
+
otlp_attributes[ATTRIBUTES_JSON_SCHEMA_KEY] = attributes_json_schema(json_schema_properties)
|
|
801
|
+
|
|
802
|
+
tags = self._tags + tuple(tags or ())
|
|
803
|
+
if tags:
|
|
804
|
+
otlp_attributes[ATTRIBUTES_TAGS_KEY] = uniquify_sequence(tags)
|
|
805
|
+
|
|
806
|
+
sample_rate = (
|
|
807
|
+
self._sample_rate
|
|
808
|
+
if self._sample_rate is not None
|
|
809
|
+
else otlp_attributes.pop(ATTRIBUTES_SAMPLE_RATE_KEY, None)
|
|
810
|
+
)
|
|
811
|
+
if sample_rate is not None and sample_rate != 1: # pragma: no cover
|
|
812
|
+
otlp_attributes[ATTRIBUTES_SAMPLE_RATE_KEY] = sample_rate
|
|
813
|
+
|
|
814
|
+
if not (self._console_log if console_log is None else console_log):
|
|
815
|
+
otlp_attributes[DISABLE_CONSOLE_KEY] = True
|
|
816
|
+
start_time = self._config.advanced.ns_timestamp_generator()
|
|
817
|
+
|
|
818
|
+
span = self._logs_tracer.start_span(
|
|
819
|
+
msg_template,
|
|
820
|
+
attributes=otlp_attributes,
|
|
821
|
+
start_time=start_time,
|
|
822
|
+
)
|
|
823
|
+
|
|
824
|
+
if not span.is_recording():
|
|
825
|
+
return
|
|
826
|
+
|
|
827
|
+
if exc_info:
|
|
828
|
+
if exc_info is True:
|
|
829
|
+
exc_info = sys.exc_info()
|
|
830
|
+
if isinstance(exc_info, tuple):
|
|
831
|
+
exc_info = exc_info[1]
|
|
832
|
+
if isinstance(exc_info, BaseException):
|
|
833
|
+
span.record_exception(exc_info)
|
|
834
|
+
if otlp_attributes[ATTRIBUTES_LOG_LEVEL_NUM_KEY] >= LEVEL_NUMBERS['error']: # pyright: ignore[reportOperatorIssue]
|
|
835
|
+
# Set the status description to the exception message.
|
|
836
|
+
# OTEL only lets us set the description when the status code is ERROR,
|
|
837
|
+
# which we only want to do when the log level is error.
|
|
838
|
+
set_exception_status(span, exc_info)
|
|
839
|
+
elif exc_info is not None: # pragma: no cover
|
|
840
|
+
raise TypeError(f'Invalid type for exc_info: {exc_info.__class__.__name__}')
|
|
841
|
+
|
|
842
|
+
span.end(start_time)
|
|
843
|
+
|
|
844
|
+
def with_tags(self, *tags: str) -> Logfire:
|
|
845
|
+
"""A new Logfire instance which always uses the given tags.
|
|
846
|
+
|
|
847
|
+
```py
|
|
848
|
+
import logfire
|
|
849
|
+
|
|
850
|
+
logfire.configure()
|
|
851
|
+
|
|
852
|
+
local_logfire = logfire.with_tags('tag1')
|
|
853
|
+
local_logfire.info('a log message', _tags=['tag2'])
|
|
854
|
+
|
|
855
|
+
# This is equivalent to:
|
|
856
|
+
logfire.info('a log message', _tags=['tag1', 'tag2'])
|
|
857
|
+
```
|
|
858
|
+
|
|
859
|
+
Args:
|
|
860
|
+
tags: The tags to add.
|
|
861
|
+
|
|
862
|
+
Returns:
|
|
863
|
+
A new Logfire instance with the `tags` added to any existing tags.
|
|
864
|
+
"""
|
|
865
|
+
return self.with_settings(tags=tags)
|
|
866
|
+
|
|
867
|
+
def with_trace_sample_rate(self, sample_rate: float) -> Logfire: # pragma: no cover
|
|
868
|
+
"""A new Logfire instance with the given sampling ratio applied.
|
|
869
|
+
|
|
870
|
+
Args:
|
|
871
|
+
sample_rate: The sampling ratio to use.
|
|
872
|
+
|
|
873
|
+
Returns:
|
|
874
|
+
A new Logfire instance with the sampling ratio applied.
|
|
875
|
+
"""
|
|
876
|
+
if sample_rate > 1 or sample_rate < 0:
|
|
877
|
+
raise ValueError('sample_rate must be between 0 and 1')
|
|
878
|
+
return Logfire(
|
|
879
|
+
config=self._config,
|
|
880
|
+
tags=self._tags,
|
|
881
|
+
sample_rate=sample_rate,
|
|
882
|
+
)
|
|
883
|
+
|
|
884
|
+
def with_settings(
|
|
885
|
+
self,
|
|
886
|
+
*,
|
|
887
|
+
tags: Sequence[str] = (),
|
|
888
|
+
console_log: bool | None = None,
|
|
889
|
+
custom_scope_suffix: str | None = None,
|
|
890
|
+
) -> Logfire:
|
|
891
|
+
"""A new Logfire instance which uses the given settings.
|
|
892
|
+
|
|
893
|
+
Args:
|
|
894
|
+
tags: Sequence of tags to include in the log.
|
|
895
|
+
console_log: Whether to log to the console, defaults to `True`.
|
|
896
|
+
custom_scope_suffix: A custom suffix to append to `logfire.` e.g. `logfire.loguru`.
|
|
897
|
+
|
|
898
|
+
It should only be used when instrumenting another library with Logfire, such as structlog or loguru.
|
|
899
|
+
|
|
900
|
+
See the `instrumenting_module_name` parameter on
|
|
901
|
+
[TracerProvider.get_tracer][opentelemetry.sdk.trace.TracerProvider.get_tracer] for more info.
|
|
902
|
+
|
|
903
|
+
Returns:
|
|
904
|
+
A new Logfire instance with the given settings applied.
|
|
905
|
+
"""
|
|
906
|
+
# TODO add sample_rate once it's more stable
|
|
907
|
+
return Logfire(
|
|
908
|
+
config=self._config,
|
|
909
|
+
tags=self._tags + tuple(tags),
|
|
910
|
+
sample_rate=self._sample_rate,
|
|
911
|
+
console_log=self._console_log if console_log is None else console_log,
|
|
912
|
+
otel_scope=self._otel_scope if custom_scope_suffix is None else f'logfire.{custom_scope_suffix}',
|
|
913
|
+
)
|
|
914
|
+
|
|
915
|
+
def force_flush(self, timeout_millis: int = 3_000) -> bool: # pragma: no cover
|
|
916
|
+
"""Force flush all telemetry and forwarding pipelines.
|
|
917
|
+
|
|
918
|
+
Args:
|
|
919
|
+
timeout_millis: The timeout in milliseconds.
|
|
920
|
+
|
|
921
|
+
Returns:
|
|
922
|
+
Whether every component that reports a status flushed successfully.
|
|
923
|
+
"""
|
|
924
|
+
return self._config.force_flush(timeout_millis)
|
|
925
|
+
|
|
926
|
+
def url_from_eval(self, report: EvaluationReport[Any, Any, Any]) -> str | None:
|
|
927
|
+
"""Generate a Logfire URL to view an evaluation report.
|
|
928
|
+
|
|
929
|
+
Args:
|
|
930
|
+
report: An evaluation report from `pydantic_evals`.
|
|
931
|
+
|
|
932
|
+
Returns:
|
|
933
|
+
The URL string, or `None` if the project URL or trace/span IDs are not available.
|
|
934
|
+
"""
|
|
935
|
+
project_url = self._config._project_url # type: ignore[reportPrivateUsage]
|
|
936
|
+
trace_id = report.trace_id
|
|
937
|
+
span_id = report.span_id
|
|
938
|
+
if not project_url or not trace_id or not span_id:
|
|
939
|
+
return None
|
|
940
|
+
evals_url = f'{project_url.rstrip("/")}/evals'
|
|
941
|
+
if dataset_name := getattr(report, 'dataset_name', None):
|
|
942
|
+
evals_url = f'{evals_url}/{quote(dataset_name, safe="")}'
|
|
943
|
+
return f'{evals_url}/compare?experiment={trace_id}-{span_id}'
|
|
944
|
+
|
|
945
|
+
def log_slow_async_callbacks(self, slow_duration: float = 0.1) -> AbstractContextManager[None]:
|
|
946
|
+
"""Log a warning whenever a function running in the asyncio event loop blocks for too long.
|
|
947
|
+
|
|
948
|
+
This works by patching the `asyncio.events.Handle._run` method.
|
|
949
|
+
|
|
950
|
+
Args:
|
|
951
|
+
slow_duration: the threshold in seconds for when a callback is considered slow.
|
|
952
|
+
|
|
953
|
+
Returns:
|
|
954
|
+
A context manager that will revert the patch when exited.
|
|
955
|
+
This context manager doesn't take into account threads or other concurrency.
|
|
956
|
+
Calling this method will immediately apply the patch
|
|
957
|
+
without waiting for the context manager to be opened,
|
|
958
|
+
i.e. it's not necessary to use this as a context manager.
|
|
959
|
+
"""
|
|
960
|
+
return async_.log_slow_callbacks(self, slow_duration)
|
|
961
|
+
|
|
962
|
+
def install_auto_tracing(
|
|
963
|
+
self,
|
|
964
|
+
modules: Sequence[str] | Callable[[AutoTraceModule], bool],
|
|
965
|
+
*,
|
|
966
|
+
min_duration: float,
|
|
967
|
+
check_imported_modules: Literal['error', 'warn', 'ignore'] = 'error',
|
|
968
|
+
) -> None:
|
|
969
|
+
"""Install automatic tracing.
|
|
970
|
+
|
|
971
|
+
See the [Auto-Tracing guide](https://pydantic.dev/docs/logfire/instrument/python/add-auto-tracing/)
|
|
972
|
+
for more info.
|
|
973
|
+
|
|
974
|
+
This will trace all non-generator function calls in the modules specified by the modules argument.
|
|
975
|
+
It's equivalent to wrapping the body of every function in matching modules in `with logfire.span(...):`.
|
|
976
|
+
|
|
977
|
+
!!! note
|
|
978
|
+
This function MUST be called before any of the modules to be traced are imported.
|
|
979
|
+
|
|
980
|
+
Generator functions will not be traced for reasons explained [here](https://logfire.pydantic.dev/docs/guides/advanced/generators/).
|
|
981
|
+
|
|
982
|
+
This works by inserting a new meta path finder into `sys.meta_path`, so inserting another finder before it
|
|
983
|
+
may prevent it from working.
|
|
984
|
+
|
|
985
|
+
It relies on being able to retrieve the source code via at least one other existing finder in the meta path,
|
|
986
|
+
so it may not work if standard finders are not present or if the source code is not available.
|
|
987
|
+
A modified version of the source code is then compiled and executed in place of the original module.
|
|
988
|
+
|
|
989
|
+
Args:
|
|
990
|
+
modules: List of module names to trace, or a function which returns True for modules that should be traced.
|
|
991
|
+
If a list is provided, any submodules within a given module will also be traced.
|
|
992
|
+
min_duration: A minimum duration in seconds for which a function must run before it's traced.
|
|
993
|
+
Setting to `0` causes all functions to be traced from the beginning.
|
|
994
|
+
Otherwise, the first time(s) each function is called, it will be timed but not traced.
|
|
995
|
+
Only after the function has run for at least `min_duration` will it be traced in subsequent calls.
|
|
996
|
+
check_imported_modules: If this is `'error'` (the default), then an exception will be raised if any of the
|
|
997
|
+
modules in `sys.modules` (i.e. modules that have already been imported) match the modules to trace.
|
|
998
|
+
Set to `'warn'` to issue a warning instead, or `'ignore'` to skip the check.
|
|
999
|
+
"""
|
|
1000
|
+
install_auto_tracing(self, modules, check_imported_modules=check_imported_modules, min_duration=min_duration)
|
|
1001
|
+
|
|
1002
|
+
def _warn_if_not_initialized_for_instrumentation(self):
|
|
1003
|
+
self.config.warn_if_not_initialized('Instrumentation will have no effect')
|
|
1004
|
+
|
|
1005
|
+
def instrument_surrealdb(
|
|
1006
|
+
self, obj: SyncTemplate | AsyncTemplate | type[SyncTemplate] | type[AsyncTemplate] | None = None
|
|
1007
|
+
) -> None:
|
|
1008
|
+
"""Instrument [SurrealDB](https://surrealdb.com/) connections, creating a span for each method.
|
|
1009
|
+
|
|
1010
|
+
Args:
|
|
1011
|
+
obj: Pass a single connection instance to instrument only that connection.
|
|
1012
|
+
Pass a connection class to instrument all instances of that class.
|
|
1013
|
+
By default, all connection classes are instrumented.
|
|
1014
|
+
"""
|
|
1015
|
+
from .integrations.surrealdb import instrument_surrealdb
|
|
1016
|
+
|
|
1017
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
1018
|
+
instrument_surrealdb(obj, self)
|
|
1019
|
+
|
|
1020
|
+
def instrument_snowflake(
|
|
1021
|
+
self,
|
|
1022
|
+
conn_or_module: ModuleType | SnowflakeConnection | None = None,
|
|
1023
|
+
*,
|
|
1024
|
+
capture_parameters: bool = False,
|
|
1025
|
+
) -> None:
|
|
1026
|
+
"""Instrument the [Snowflake Connector for Python](https://docs.snowflake.com/en/developer-guide/python-connector/python-connector) so that a span is created for each query.
|
|
1027
|
+
|
|
1028
|
+
Calls to `execute_async()` create a `snowflake execute async` span that measures query submission,
|
|
1029
|
+
not server-side execution.
|
|
1030
|
+
|
|
1031
|
+
Args:
|
|
1032
|
+
conn_or_module: Pass a single connection instance to instrument only that connection.
|
|
1033
|
+
By default (`None`), all connections are instrumented, including ones created later.
|
|
1034
|
+
capture_parameters: Set to `True` to capture query parameters as span attributes.
|
|
1035
|
+
Be cautious when enabling this, as it may lead to sensitive data being captured in traces.
|
|
1036
|
+
Instrumenting the same target again has no effect; the first call determines this setting,
|
|
1037
|
+
and a later call with a different value emits a warning.
|
|
1038
|
+
A connection keeps the setting it was instrumented with, even if the module is instrumented later.
|
|
1039
|
+
"""
|
|
1040
|
+
from .integrations.snowflake import instrument_snowflake
|
|
1041
|
+
|
|
1042
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
1043
|
+
instrument_snowflake(self, conn_or_module, capture_parameters)
|
|
1044
|
+
|
|
1045
|
+
def instrument_mcp(self, *, propagate_otel_context: bool = True) -> None:
|
|
1046
|
+
"""Instrument the [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk).
|
|
1047
|
+
|
|
1048
|
+
Instruments both the client and server side. If possible, calling this in both the client and server
|
|
1049
|
+
processes is recommended for nice distributed traces.
|
|
1050
|
+
|
|
1051
|
+
This is only needed with mcp 1.x. Version 2 of the SDK (which fastmcp 4 depends on) emits
|
|
1052
|
+
OpenTelemetry spans and propagates the trace context via `_meta` by itself, so with it
|
|
1053
|
+
`logfire.configure()` is all that's needed. Calling this method there does nothing
|
|
1054
|
+
except emit a `UserWarning` saying so.
|
|
1055
|
+
|
|
1056
|
+
Args:
|
|
1057
|
+
propagate_otel_context: Whether to enable propagation of the OpenTelemetry context
|
|
1058
|
+
for distributed tracing.
|
|
1059
|
+
Set to False to prevent setting extra fields like `traceparent` on the metadata of requests.
|
|
1060
|
+
Ignored with mcp 2, which always propagates the context.
|
|
1061
|
+
"""
|
|
1062
|
+
from .integrations.mcp import instrument_mcp
|
|
1063
|
+
|
|
1064
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
1065
|
+
instrument_mcp(self, propagate_otel_context)
|
|
1066
|
+
|
|
1067
|
+
def instrument_claude_agent_sdk(self) -> AbstractContextManager[None]:
|
|
1068
|
+
"""Instrument the [Claude Agent SDK](https://platform.claude.com/docs/en/agent-sdk/overview).
|
|
1069
|
+
|
|
1070
|
+
All `ClaudeSDKClient` instances created after this call will be automatically traced.
|
|
1071
|
+
Existing instances created before this call will not have tool call tracing.
|
|
1072
|
+
|
|
1073
|
+
Returns:
|
|
1074
|
+
A context manager that will revert the instrumentation when exited.
|
|
1075
|
+
This context manager doesn't take into account threads or other concurrency.
|
|
1076
|
+
Calling this method will immediately apply the instrumentation
|
|
1077
|
+
without waiting for the context manager to be opened,
|
|
1078
|
+
i.e. it's not necessary to use this as a context manager.
|
|
1079
|
+
"""
|
|
1080
|
+
from .integrations.claude_agent_sdk import instrument_claude_agent_sdk
|
|
1081
|
+
|
|
1082
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
1083
|
+
return instrument_claude_agent_sdk(self)
|
|
1084
|
+
|
|
1085
|
+
def instrument_pydantic(
|
|
1086
|
+
self,
|
|
1087
|
+
record: PydanticPluginRecordValues = 'all',
|
|
1088
|
+
include: Iterable[str] = (),
|
|
1089
|
+
exclude: Iterable[str] = (),
|
|
1090
|
+
) -> None:
|
|
1091
|
+
"""Instrument Pydantic model validations.
|
|
1092
|
+
|
|
1093
|
+
This must be called before defining and importing the model classes you want to instrument.
|
|
1094
|
+
See the [Pydantic integration guide](https://logfire.pydantic.dev/docs/integrations/pydantic/) for more info.
|
|
1095
|
+
|
|
1096
|
+
Args:
|
|
1097
|
+
record: The record mode for the Pydantic plugin. It can be one of the following values:
|
|
1098
|
+
|
|
1099
|
+
- `all`: Send traces and metrics for all events. This is default value.
|
|
1100
|
+
- `failure`: Send metrics for all validations and traces only for validation failures.
|
|
1101
|
+
- `metrics`: Send only metrics.
|
|
1102
|
+
- `off`: Disable instrumentation.
|
|
1103
|
+
include:
|
|
1104
|
+
By default, third party modules are not instrumented. This option allows you to include specific modules.
|
|
1105
|
+
Each entry is a regular expression matched against `module::ModelName` and anchored at the end,
|
|
1106
|
+
so use e.g. `openai.*` rather than `openai`, which would only match a model named `openai`.
|
|
1107
|
+
exclude:
|
|
1108
|
+
Exclude specific modules from instrumentation. Matched the same way as `include`.
|
|
1109
|
+
"""
|
|
1110
|
+
# Note that unlike most instrument_* methods, we intentionally don't call
|
|
1111
|
+
# _warn_if_not_initialized_for_instrumentation, because this method needs to be called early.
|
|
1112
|
+
|
|
1113
|
+
if record != 'off':
|
|
1114
|
+
import pydantic
|
|
1115
|
+
|
|
1116
|
+
if get_version(pydantic.__version__) < get_version('2.5.0'):
|
|
1117
|
+
raise RuntimeError('The Pydantic plugin requires Pydantic 2.5.0 or newer.')
|
|
1118
|
+
|
|
1119
|
+
from logfire.integrations.pydantic import PydanticPlugin, set_pydantic_plugin_config
|
|
1120
|
+
|
|
1121
|
+
if isinstance(include, str):
|
|
1122
|
+
include = {include}
|
|
1123
|
+
|
|
1124
|
+
if isinstance(exclude, str):
|
|
1125
|
+
exclude = {exclude}
|
|
1126
|
+
|
|
1127
|
+
# TODO instrument using this instance, i.e. pass `self` somewhere, rather than always using the global instance
|
|
1128
|
+
set_pydantic_plugin_config(
|
|
1129
|
+
PydanticPlugin(
|
|
1130
|
+
record=record,
|
|
1131
|
+
include=set(include),
|
|
1132
|
+
exclude=set(exclude),
|
|
1133
|
+
)
|
|
1134
|
+
)
|
|
1135
|
+
|
|
1136
|
+
@overload
|
|
1137
|
+
def instrument_pydantic_ai(
|
|
1138
|
+
self,
|
|
1139
|
+
obj: pydantic_ai.Agent | None = None,
|
|
1140
|
+
/,
|
|
1141
|
+
*,
|
|
1142
|
+
include_binary_content: bool | None = None,
|
|
1143
|
+
include_content: bool | None = None,
|
|
1144
|
+
version: Literal[1, 2, 3, 4, 5] | None = None,
|
|
1145
|
+
event_mode: Literal['attributes', 'logs'] | None = None,
|
|
1146
|
+
**kwargs: Any,
|
|
1147
|
+
) -> None: ...
|
|
1148
|
+
|
|
1149
|
+
@overload
|
|
1150
|
+
def instrument_pydantic_ai(
|
|
1151
|
+
self,
|
|
1152
|
+
obj: pydantic_ai.models.Model,
|
|
1153
|
+
/,
|
|
1154
|
+
*,
|
|
1155
|
+
include_binary_content: bool | None = None,
|
|
1156
|
+
include_content: bool | None = None,
|
|
1157
|
+
version: Literal[1, 2, 3, 4, 5] | None = None,
|
|
1158
|
+
event_mode: Literal['attributes', 'logs'] | None = None,
|
|
1159
|
+
**kwargs: Any,
|
|
1160
|
+
) -> pydantic_ai.models.Model: ...
|
|
1161
|
+
|
|
1162
|
+
def instrument_pydantic_ai(
|
|
1163
|
+
self,
|
|
1164
|
+
obj: pydantic_ai.Agent | pydantic_ai.models.Model | None = None,
|
|
1165
|
+
/,
|
|
1166
|
+
*,
|
|
1167
|
+
include_binary_content: bool | None = None,
|
|
1168
|
+
include_content: bool | None = None,
|
|
1169
|
+
version: Literal[1, 2, 3, 4, 5] | None = None,
|
|
1170
|
+
event_mode: Literal['attributes', 'logs'] | None = None,
|
|
1171
|
+
**kwargs: Any,
|
|
1172
|
+
) -> pydantic_ai.models.Model | None:
|
|
1173
|
+
"""Instrument Pydantic AI.
|
|
1174
|
+
|
|
1175
|
+
Args:
|
|
1176
|
+
obj: What to instrument.
|
|
1177
|
+
By default, all agents are instrumented.
|
|
1178
|
+
You can also pass a specific model or agent.
|
|
1179
|
+
If you pass a model, a new instrumented model will be returned.
|
|
1180
|
+
include_binary_content: Whether to include base64 encoded binary content (e.g. images) in the telemetry.
|
|
1181
|
+
On by default. Requires Pydantic AI 0.2.5 or newer.
|
|
1182
|
+
include_content: Whether to include prompts, completions, and tool call arguments and responses
|
|
1183
|
+
in the telemetry. On by default. Requires Pydantic AI 0.3.4 or newer.
|
|
1184
|
+
version: Version of the data format. This is unrelated to the Pydantic AI package version.
|
|
1185
|
+
Supported values depend on the installed Pydantic AI version.
|
|
1186
|
+
Version 1 is available only in older Pydantic AI releases and is based on the legacy
|
|
1187
|
+
event-based OpenTelemetry GenAI spec.
|
|
1188
|
+
Version 2 uses the newer OpenTelemetry GenAI spec and stores messages in the following attributes:
|
|
1189
|
+
- `gen_ai.system_instructions` for instructions passed to the agent.
|
|
1190
|
+
- `gen_ai.input.messages` and `gen_ai.output.messages` on model request spans.
|
|
1191
|
+
- `pydantic_ai.all_messages` on agent run spans.
|
|
1192
|
+
Version 3 changes the names of some attributes and spans but not the shape of the data.
|
|
1193
|
+
Versions 2 through 4 are deprecated in Pydantic AI 2.x, where version 5 is the default.
|
|
1194
|
+
event_mode: The mode for emitting events in version 1 with older Pydantic AI releases.
|
|
1195
|
+
If `'attributes'`, events are attached to the span as attributes.
|
|
1196
|
+
If `'logs'`, events are emitted as OpenTelemetry log-based events.
|
|
1197
|
+
kwargs: Additional keyword arguments to pass to
|
|
1198
|
+
[`InstrumentationSettings`](https://pydantic.dev/docs/ai/api/models/instrumented/#pydantic_ai.models.instrumented.InstrumentationSettings)
|
|
1199
|
+
for future compatibility.
|
|
1200
|
+
"""
|
|
1201
|
+
from .integrations.pydantic_ai import instrument_pydantic_ai
|
|
1202
|
+
|
|
1203
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
1204
|
+
|
|
1205
|
+
return instrument_pydantic_ai(
|
|
1206
|
+
self,
|
|
1207
|
+
obj=obj,
|
|
1208
|
+
event_mode=event_mode,
|
|
1209
|
+
version=version,
|
|
1210
|
+
include_content=include_content,
|
|
1211
|
+
include_binary_content=include_binary_content,
|
|
1212
|
+
**kwargs,
|
|
1213
|
+
)
|
|
1214
|
+
|
|
1215
|
+
def instrument_monty(self) -> None:
|
|
1216
|
+
"""Instrument Pydantic Monty.
|
|
1217
|
+
|
|
1218
|
+
Call this once after [`configure()`][logfire.configure] and before creating a Monty pool.
|
|
1219
|
+
The first call selects the Logfire instance and its settings for the whole process;
|
|
1220
|
+
subsequent calls do not replace them.
|
|
1221
|
+
|
|
1222
|
+
It records Monty sessions, executed code, inputs, outputs, external calls,
|
|
1223
|
+
exceptions, printed text, and pool metrics. Recorded values are subject to Logfire's configured scrubbing.
|
|
1224
|
+
"""
|
|
1225
|
+
from .integrations.monty import instrument_monty
|
|
1226
|
+
|
|
1227
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
1228
|
+
instrument_monty(self)
|
|
1229
|
+
|
|
1230
|
+
def instrument_fastapi(
|
|
1231
|
+
self,
|
|
1232
|
+
app: FastAPI,
|
|
1233
|
+
*,
|
|
1234
|
+
capture_headers: bool = False,
|
|
1235
|
+
request_attributes_mapper: Callable[
|
|
1236
|
+
[
|
|
1237
|
+
Request | WebSocket,
|
|
1238
|
+
dict[str, Any],
|
|
1239
|
+
],
|
|
1240
|
+
dict[str, Any] | None,
|
|
1241
|
+
]
|
|
1242
|
+
| None = None,
|
|
1243
|
+
excluded_urls: str | Iterable[str] | None = None,
|
|
1244
|
+
record_send_receive: bool = False,
|
|
1245
|
+
extra_spans: bool = False,
|
|
1246
|
+
**opentelemetry_kwargs: Any,
|
|
1247
|
+
) -> AbstractContextManager[None]:
|
|
1248
|
+
"""Instrument a FastAPI app so that spans and logs are automatically created for each request.
|
|
1249
|
+
|
|
1250
|
+
Uses the [OpenTelemetry FastAPI Instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/fastapi/fastapi.html)
|
|
1251
|
+
under the hood, with some additional features.
|
|
1252
|
+
|
|
1253
|
+
Args:
|
|
1254
|
+
app: The FastAPI app to instrument.
|
|
1255
|
+
capture_headers: Set to `True` to capture all request and response headers.
|
|
1256
|
+
request_attributes_mapper: A function that takes a [`Request`][fastapi.Request] or [`WebSocket`][fastapi.WebSocket]
|
|
1257
|
+
and a dictionary of attributes and returns a new dictionary of attributes.
|
|
1258
|
+
The input dictionary will contain:
|
|
1259
|
+
|
|
1260
|
+
- `values`: A dictionary mapping argument names of the endpoint function to parsed and validated values.
|
|
1261
|
+
- `errors`: A list of validation errors for any invalid inputs.
|
|
1262
|
+
|
|
1263
|
+
The returned dictionary will be used as the attributes for a log message.
|
|
1264
|
+
If `None` is returned, no log message will be created.
|
|
1265
|
+
|
|
1266
|
+
You can use this to e.g. only log validation errors, or nothing at all.
|
|
1267
|
+
You can also add custom attributes.
|
|
1268
|
+
|
|
1269
|
+
The default implementation will return the input dictionary unchanged.
|
|
1270
|
+
The function mustn't modify the contents of `values` or `errors`.
|
|
1271
|
+
excluded_urls: A string of comma-separated regexes which will exclude a request from tracing if the full URL
|
|
1272
|
+
matches any of the regexes. This applies to both the Logfire and OpenTelemetry instrumentation.
|
|
1273
|
+
If not provided, the environment variables
|
|
1274
|
+
`OTEL_PYTHON_FASTAPI_EXCLUDED_URLS` and `OTEL_PYTHON_EXCLUDED_URLS` will be checked.
|
|
1275
|
+
record_send_receive: Set to `True` to allow the OpenTelemetry ASGI middleware to create send/receive spans.
|
|
1276
|
+
|
|
1277
|
+
These are disabled by default to reduce overhead and the number of spans created,
|
|
1278
|
+
since many can be created for a single request, and they are not often useful.
|
|
1279
|
+
If enabled, they will be set to debug level, meaning they will usually still be hidden in the UI.
|
|
1280
|
+
extra_spans: Whether to include the extra 'FastAPI arguments' and 'endpoint function' spans.
|
|
1281
|
+
opentelemetry_kwargs: Additional keyword arguments to pass to the OpenTelemetry FastAPI instrumentation.
|
|
1282
|
+
|
|
1283
|
+
Returns:
|
|
1284
|
+
A context manager that will revert the instrumentation when exited.
|
|
1285
|
+
This context manager doesn't take into account threads or other concurrency.
|
|
1286
|
+
Calling this method will immediately apply the instrumentation
|
|
1287
|
+
without waiting for the context manager to be opened,
|
|
1288
|
+
i.e. it's not necessary to use this as a context manager.
|
|
1289
|
+
"""
|
|
1290
|
+
from .integrations.fastapi import instrument_fastapi
|
|
1291
|
+
|
|
1292
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
1293
|
+
return instrument_fastapi(
|
|
1294
|
+
self,
|
|
1295
|
+
app,
|
|
1296
|
+
capture_headers=capture_headers,
|
|
1297
|
+
request_attributes_mapper=request_attributes_mapper,
|
|
1298
|
+
excluded_urls=excluded_urls,
|
|
1299
|
+
record_send_receive=record_send_receive,
|
|
1300
|
+
extra_spans=extra_spans,
|
|
1301
|
+
**opentelemetry_kwargs,
|
|
1302
|
+
)
|
|
1303
|
+
|
|
1304
|
+
def instrument_openai(
|
|
1305
|
+
self,
|
|
1306
|
+
openai_client: openai.OpenAI
|
|
1307
|
+
| openai.AsyncOpenAI
|
|
1308
|
+
| type[openai.OpenAI]
|
|
1309
|
+
| type[openai.AsyncOpenAI]
|
|
1310
|
+
| None = None,
|
|
1311
|
+
*,
|
|
1312
|
+
suppress_other_instrumentation: bool = True,
|
|
1313
|
+
version: SemconvVersion | Sequence[SemconvVersion] = 2,
|
|
1314
|
+
) -> AbstractContextManager[None]:
|
|
1315
|
+
"""Instrument an OpenAI client so that spans are automatically created for each request.
|
|
1316
|
+
|
|
1317
|
+
This instruments the [standard OpenAI SDK](https://pypi.org/project/openai/) package, for instrumentation
|
|
1318
|
+
of the OpenAI "agents" framework, see [`instrument_openai_agents()`][logfire.Logfire.instrument_openai_agents].
|
|
1319
|
+
|
|
1320
|
+
The following methods are instrumented for both the sync and the async clients:
|
|
1321
|
+
|
|
1322
|
+
- [`client.chat.completions.create`](https://platform.openai.com/docs/guides/text-generation/chat-completions-api) — with and without `stream=True`
|
|
1323
|
+
- [`client.completions.create`](https://platform.openai.com/docs/guides/text-generation/completions-api) — with and without `stream=True`
|
|
1324
|
+
- [`client.embeddings.create`](https://platform.openai.com/docs/guides/embeddings/how-to-get-embeddings)
|
|
1325
|
+
- [`client.images.generate`](https://platform.openai.com/docs/guides/images/generations)
|
|
1326
|
+
|
|
1327
|
+
When `stream=True` a second span is created to instrument the streamed response.
|
|
1328
|
+
|
|
1329
|
+
Example usage:
|
|
1330
|
+
|
|
1331
|
+
```python skip-run="true" skip-reason="external-connection"
|
|
1332
|
+
import openai
|
|
1333
|
+
|
|
1334
|
+
import logfire
|
|
1335
|
+
|
|
1336
|
+
client = openai.OpenAI()
|
|
1337
|
+
logfire.configure()
|
|
1338
|
+
logfire.instrument_openai(client)
|
|
1339
|
+
|
|
1340
|
+
response = client.chat.completions.create(
|
|
1341
|
+
model='gpt-4',
|
|
1342
|
+
messages=[
|
|
1343
|
+
{'role': 'system', 'content': 'You are a helpful assistant.'},
|
|
1344
|
+
{'role': 'user', 'content': 'What is four plus five?'},
|
|
1345
|
+
],
|
|
1346
|
+
)
|
|
1347
|
+
print('answer:', response.choices[0].message.content)
|
|
1348
|
+
```
|
|
1349
|
+
|
|
1350
|
+
Args:
|
|
1351
|
+
openai_client: The OpenAI client or class to instrument:
|
|
1352
|
+
|
|
1353
|
+
- `None` (the default) to instrument both the `openai.OpenAI` and `openai.AsyncOpenAI` classes.
|
|
1354
|
+
- The `openai.OpenAI` class or a subclass
|
|
1355
|
+
- The `openai.AsyncOpenAI` class or a subclass
|
|
1356
|
+
- An instance of `openai.OpenAI`
|
|
1357
|
+
- An instance of `openai.AsyncOpenAI`
|
|
1358
|
+
|
|
1359
|
+
suppress_other_instrumentation: If True, suppress any other OTEL instrumentation that may be otherwise
|
|
1360
|
+
enabled. In reality, this means the HTTPX instrumentation, which could otherwise be called since
|
|
1361
|
+
OpenAI uses HTTPX to make HTTP requests.
|
|
1362
|
+
|
|
1363
|
+
version: The version(s) of the span attribute format to use:
|
|
1364
|
+
|
|
1365
|
+
- `1`: Uses the legacy `request_data` and `response_data` attributes.
|
|
1366
|
+
- `2` (the default): Uses OpenTelemetry Gen AI semantic convention attributes
|
|
1367
|
+
(`gen_ai.input.messages`, `gen_ai.output.messages`, etc.) and omits the full
|
|
1368
|
+
`response_data` attribute. A minimal `request_data` (e.g. `{"model": ...}`) is
|
|
1369
|
+
still recorded for message template compatibility.
|
|
1370
|
+
- `'latest'`: Uses the latest format, which is currently identical to version 2.
|
|
1371
|
+
Unlike a numbered version, this format may change between releases.
|
|
1372
|
+
- `[1, 2]` or `[1, 'latest']`: Emits both the full legacy attributes and the semantic
|
|
1373
|
+
convention attributes simultaneously, useful for migration and testing.
|
|
1374
|
+
|
|
1375
|
+
Returns:
|
|
1376
|
+
A context manager that will revert the instrumentation when exited.
|
|
1377
|
+
Use of this context manager is optional.
|
|
1378
|
+
"""
|
|
1379
|
+
import openai
|
|
1380
|
+
|
|
1381
|
+
from .integrations.llm_providers.llm_provider import instrument_llm_provider
|
|
1382
|
+
from .integrations.llm_providers.openai import get_endpoint_config, is_async_client, on_response
|
|
1383
|
+
from .integrations.llm_providers.semconv import normalize_versions
|
|
1384
|
+
|
|
1385
|
+
normalized_versions = normalize_versions(version)
|
|
1386
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
1387
|
+
return instrument_llm_provider(
|
|
1388
|
+
self,
|
|
1389
|
+
openai_client or (openai.OpenAI, openai.AsyncOpenAI),
|
|
1390
|
+
suppress_other_instrumentation,
|
|
1391
|
+
'OpenAI',
|
|
1392
|
+
partial(get_endpoint_config, version=normalized_versions),
|
|
1393
|
+
partial(on_response, version=normalized_versions),
|
|
1394
|
+
is_async_client,
|
|
1395
|
+
)
|
|
1396
|
+
|
|
1397
|
+
def instrument_openai_agents(self) -> None:
|
|
1398
|
+
"""Instrument the [`agents`](https://github.com/openai/openai-agents-python) framework from OpenAI.
|
|
1399
|
+
|
|
1400
|
+
For instrumentation of the standard OpenAI SDK package,
|
|
1401
|
+
see [`instrument_openai()`][logfire.Logfire.instrument_openai].
|
|
1402
|
+
"""
|
|
1403
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
1404
|
+
|
|
1405
|
+
from .integrations.openai_agents import LogfireTraceProviderWrapper
|
|
1406
|
+
|
|
1407
|
+
LogfireTraceProviderWrapper.install(self)
|
|
1408
|
+
|
|
1409
|
+
def instrument_anthropic(
|
|
1410
|
+
self,
|
|
1411
|
+
anthropic_client: (
|
|
1412
|
+
anthropic.Anthropic
|
|
1413
|
+
| anthropic.AsyncAnthropic
|
|
1414
|
+
| _AnthropicBedrock
|
|
1415
|
+
| _AsyncAnthropicBedrock
|
|
1416
|
+
| type[anthropic.Anthropic]
|
|
1417
|
+
| type[anthropic.AsyncAnthropic]
|
|
1418
|
+
| type[_AnthropicBedrock]
|
|
1419
|
+
| type[_AsyncAnthropicBedrock]
|
|
1420
|
+
| None
|
|
1421
|
+
) = None,
|
|
1422
|
+
*,
|
|
1423
|
+
suppress_other_instrumentation: bool = True,
|
|
1424
|
+
version: SemconvVersion | Sequence[SemconvVersion] = 2,
|
|
1425
|
+
) -> AbstractContextManager[None]:
|
|
1426
|
+
"""Instrument an Anthropic client so that spans are automatically created for each request.
|
|
1427
|
+
|
|
1428
|
+
The following methods are instrumented for both the sync and async clients:
|
|
1429
|
+
|
|
1430
|
+
- [`client.messages.create`](https://docs.anthropic.com/en/api/messages)
|
|
1431
|
+
- [`client.messages.stream`](https://docs.anthropic.com/en/api/messages-streaming)
|
|
1432
|
+
- [`client.beta.tools.messages.create`](https://docs.anthropic.com/en/docs/tool-use)
|
|
1433
|
+
|
|
1434
|
+
When `stream=True` a second span is created to instrument the streamed response.
|
|
1435
|
+
|
|
1436
|
+
Example usage:
|
|
1437
|
+
|
|
1438
|
+
```python skip-run="true" skip-reason="external-connection"
|
|
1439
|
+
import anthropic
|
|
1440
|
+
|
|
1441
|
+
import logfire
|
|
1442
|
+
|
|
1443
|
+
client = anthropic.Anthropic()
|
|
1444
|
+
|
|
1445
|
+
logfire.configure()
|
|
1446
|
+
logfire.instrument_anthropic(client)
|
|
1447
|
+
|
|
1448
|
+
response = client.messages.create(
|
|
1449
|
+
model='claude-3-haiku-20240307',
|
|
1450
|
+
system='You are a helpful assistant.',
|
|
1451
|
+
messages=[
|
|
1452
|
+
{'role': 'user', 'content': 'What is four plus five?'},
|
|
1453
|
+
],
|
|
1454
|
+
)
|
|
1455
|
+
print('answer:', response.content[0].text)
|
|
1456
|
+
```
|
|
1457
|
+
|
|
1458
|
+
Args:
|
|
1459
|
+
anthropic_client: The Anthropic client or class to instrument:
|
|
1460
|
+
- `None` (the default) to instrument all Anthropic client types
|
|
1461
|
+
- The `anthropic.Anthropic` or `anthropic.AnthropicBedrock` class or subclass
|
|
1462
|
+
- The `anthropic.AsyncAnthropic` or `anthropic.AsyncAnthropicBedrock` class or subclass
|
|
1463
|
+
- An instance of any of the above classes
|
|
1464
|
+
|
|
1465
|
+
suppress_other_instrumentation: If True, suppress any other OTEL instrumentation that may be otherwise
|
|
1466
|
+
enabled. In reality, this means the HTTPX instrumentation, which could otherwise be called since
|
|
1467
|
+
OpenAI uses HTTPX to make HTTP requests.
|
|
1468
|
+
|
|
1469
|
+
version: The version(s) of the span attribute format to use:
|
|
1470
|
+
|
|
1471
|
+
- `1`: Uses the legacy `request_data` and `response_data` attributes.
|
|
1472
|
+
- `2` (the default): Uses OpenTelemetry Gen AI semantic convention attributes
|
|
1473
|
+
(`gen_ai.input.messages`, `gen_ai.output.messages`, etc.) and omits the full
|
|
1474
|
+
`response_data` attribute. A minimal `request_data` (e.g. `{"model": ...}`) is
|
|
1475
|
+
still recorded for message template compatibility.
|
|
1476
|
+
- `'latest'`: Uses the latest format, which is currently identical to version 2.
|
|
1477
|
+
Unlike a numbered version, this format may change between releases.
|
|
1478
|
+
- `[1, 2]` or `[1, 'latest']`: Emits both the full legacy attributes and the semantic
|
|
1479
|
+
convention attributes simultaneously, useful for migration and testing.
|
|
1480
|
+
|
|
1481
|
+
Returns:
|
|
1482
|
+
A context manager that will revert the instrumentation when exited.
|
|
1483
|
+
Use of this context manager is optional.
|
|
1484
|
+
"""
|
|
1485
|
+
import anthropic
|
|
1486
|
+
from anthropic.lib.bedrock import AnthropicBedrock, AsyncAnthropicBedrock
|
|
1487
|
+
|
|
1488
|
+
from .integrations.llm_providers.anthropic import get_endpoint_config, is_async_client, on_response
|
|
1489
|
+
from .integrations.llm_providers.llm_provider import instrument_llm_provider
|
|
1490
|
+
from .integrations.llm_providers.semconv import normalize_versions
|
|
1491
|
+
|
|
1492
|
+
normalized_versions = normalize_versions(version)
|
|
1493
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
1494
|
+
return instrument_llm_provider(
|
|
1495
|
+
self,
|
|
1496
|
+
anthropic_client
|
|
1497
|
+
or (
|
|
1498
|
+
anthropic.Anthropic,
|
|
1499
|
+
anthropic.AsyncAnthropic,
|
|
1500
|
+
AnthropicBedrock,
|
|
1501
|
+
AsyncAnthropicBedrock,
|
|
1502
|
+
),
|
|
1503
|
+
suppress_other_instrumentation,
|
|
1504
|
+
'Anthropic',
|
|
1505
|
+
partial(get_endpoint_config, version=normalized_versions),
|
|
1506
|
+
partial(on_response, version=normalized_versions),
|
|
1507
|
+
is_async_client,
|
|
1508
|
+
)
|
|
1509
|
+
|
|
1510
|
+
def instrument_google_genai(self, **kwargs: Any):
|
|
1511
|
+
"""Instrument the [Google Gen AI SDK (`google-genai`)](https://googleapis.github.io/python-genai/).
|
|
1512
|
+
|
|
1513
|
+
!!! note
|
|
1514
|
+
To capture message contents (i.e. prompts and completions), set the environment variable
|
|
1515
|
+
`OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT` to `SPAN_ONLY`.
|
|
1516
|
+
|
|
1517
|
+
Uses the `GoogleGenAiSdkInstrumentor().instrument()` method of the
|
|
1518
|
+
[`opentelemetry-instrumentation-google-genai`](https://pypi.org/project/opentelemetry-instrumentation-google-genai/)
|
|
1519
|
+
package, to which it passes `**kwargs`.
|
|
1520
|
+
"""
|
|
1521
|
+
from .integrations.google_genai import instrument_google_genai
|
|
1522
|
+
|
|
1523
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
1524
|
+
instrument_google_genai(self, **kwargs)
|
|
1525
|
+
|
|
1526
|
+
def instrument_litellm(self, **kwargs: Any):
|
|
1527
|
+
"""Instrument the [LiteLLM](https://docs.litellm.ai/) Python SDK.
|
|
1528
|
+
|
|
1529
|
+
!!! warning
|
|
1530
|
+
This currently works best if all arguments of instrumented methods are passed as keyword arguments,
|
|
1531
|
+
e.g. `litellm.completion(model=model, messages=messages)`.
|
|
1532
|
+
|
|
1533
|
+
Uses the `LiteLLMInstrumentor().instrument()` method of the
|
|
1534
|
+
[`openinference-instrumentation-litellm`](https://pypi.org/project/openinference-instrumentation-litellm/)
|
|
1535
|
+
package, to which it passes `**kwargs`.
|
|
1536
|
+
"""
|
|
1537
|
+
from .integrations.litellm import instrument_litellm
|
|
1538
|
+
|
|
1539
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
1540
|
+
instrument_litellm(self, **kwargs)
|
|
1541
|
+
|
|
1542
|
+
def instrument_dspy(self, **kwargs: Any):
|
|
1543
|
+
"""Instrument [DSPy](https://dspy.ai/).
|
|
1544
|
+
|
|
1545
|
+
Uses the `DSPyInstrumentor().instrument()` method of the
|
|
1546
|
+
[`openinference-instrumentation-dspy`](https://pypi.org/project/openinference-instrumentation-dspy/)
|
|
1547
|
+
package, to which it passes `**kwargs`.
|
|
1548
|
+
"""
|
|
1549
|
+
from .integrations.dspy import instrument_dspy
|
|
1550
|
+
|
|
1551
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
1552
|
+
instrument_dspy(self, **kwargs)
|
|
1553
|
+
|
|
1554
|
+
def instrument_print(self) -> AbstractContextManager[None]:
|
|
1555
|
+
"""Instrument the built-in `print` function so that calls to it are logged.
|
|
1556
|
+
|
|
1557
|
+
If Logfire is configured with [`inspect_arguments=True`][logfire.configure(inspect_arguments)],
|
|
1558
|
+
the names of the arguments passed to `print` will be included in the log attributes
|
|
1559
|
+
and will be used for scrubbing.
|
|
1560
|
+
|
|
1561
|
+
The fallback attribute name `logfire.print_args` will be used if:
|
|
1562
|
+
|
|
1563
|
+
- `inspect_arguments` is `False`
|
|
1564
|
+
- Inspection fails for any reason
|
|
1565
|
+
- Multiple starred arguments are used (e.g. `print(*args1, *args2)`)
|
|
1566
|
+
in which case names can't be unambiguously determined.
|
|
1567
|
+
|
|
1568
|
+
Returns:
|
|
1569
|
+
A context manager that will revert the instrumentation when exited.
|
|
1570
|
+
Use of this context manager is optional.
|
|
1571
|
+
"""
|
|
1572
|
+
from .integrations.print import instrument_print
|
|
1573
|
+
|
|
1574
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
1575
|
+
return instrument_print(self)
|
|
1576
|
+
|
|
1577
|
+
def instrument_asyncpg(self, capture_parameters: bool = False, **kwargs: Any) -> None:
|
|
1578
|
+
"""Instrument the `asyncpg` module so that spans are automatically created for each query.
|
|
1579
|
+
|
|
1580
|
+
Args:
|
|
1581
|
+
capture_parameters: Set to `True` to capture query parameters as span attributes.
|
|
1582
|
+
Be cautious when enabling this, as it may lead to sensitive data being captured in traces.
|
|
1583
|
+
kwargs: Additional keyword arguments to pass to the OpenTelemetry `instrument` method.
|
|
1584
|
+
"""
|
|
1585
|
+
from .integrations.asyncpg import instrument_asyncpg
|
|
1586
|
+
|
|
1587
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
1588
|
+
return instrument_asyncpg(
|
|
1589
|
+
**{
|
|
1590
|
+
'tracer_provider': self._config.get_tracer_provider(),
|
|
1591
|
+
'meter_provider': self._config.get_meter_provider(),
|
|
1592
|
+
'capture_parameters': capture_parameters,
|
|
1593
|
+
**kwargs,
|
|
1594
|
+
},
|
|
1595
|
+
)
|
|
1596
|
+
|
|
1597
|
+
@overload
|
|
1598
|
+
def instrument_httpx(
|
|
1599
|
+
self,
|
|
1600
|
+
client: httpx.Client | httpx2.Client,
|
|
1601
|
+
*,
|
|
1602
|
+
capture_all: bool = False,
|
|
1603
|
+
capture_headers: bool = False,
|
|
1604
|
+
capture_request_body: bool = False,
|
|
1605
|
+
capture_response_body: bool = False,
|
|
1606
|
+
request_hook: HttpxRequestHook | None = None,
|
|
1607
|
+
response_hook: HttpxResponseHook | None = None,
|
|
1608
|
+
**kwargs: Any,
|
|
1609
|
+
) -> None: ...
|
|
1610
|
+
|
|
1611
|
+
@overload
|
|
1612
|
+
def instrument_httpx(
|
|
1613
|
+
self,
|
|
1614
|
+
client: httpx.AsyncClient | httpx2.AsyncClient,
|
|
1615
|
+
*,
|
|
1616
|
+
capture_all: bool = False,
|
|
1617
|
+
capture_headers: bool = False,
|
|
1618
|
+
capture_request_body: bool = False,
|
|
1619
|
+
capture_response_body: bool = False,
|
|
1620
|
+
request_hook: HttpxRequestHook | HttpxAsyncRequestHook | None = None,
|
|
1621
|
+
response_hook: HttpxResponseHook | HttpxAsyncResponseHook | None = None,
|
|
1622
|
+
**kwargs: Any,
|
|
1623
|
+
) -> None: ...
|
|
1624
|
+
|
|
1625
|
+
@overload
|
|
1626
|
+
def instrument_httpx(
|
|
1627
|
+
self,
|
|
1628
|
+
client: None = None,
|
|
1629
|
+
*,
|
|
1630
|
+
capture_all: bool = False,
|
|
1631
|
+
capture_headers: bool = False,
|
|
1632
|
+
capture_request_body: bool = False,
|
|
1633
|
+
capture_response_body: bool = False,
|
|
1634
|
+
request_hook: HttpxRequestHook | None = None,
|
|
1635
|
+
response_hook: HttpxResponseHook | None = None,
|
|
1636
|
+
async_request_hook: HttpxAsyncRequestHook | None = None,
|
|
1637
|
+
async_response_hook: HttpxAsyncResponseHook | None = None,
|
|
1638
|
+
**kwargs: Any,
|
|
1639
|
+
) -> None: ...
|
|
1640
|
+
|
|
1641
|
+
def instrument_httpx(
|
|
1642
|
+
self,
|
|
1643
|
+
client: httpx.Client | httpx.AsyncClient | httpx2.Client | httpx2.AsyncClient | None = None,
|
|
1644
|
+
*,
|
|
1645
|
+
capture_all: bool | None = None,
|
|
1646
|
+
capture_headers: bool = False,
|
|
1647
|
+
capture_request_body: bool = False,
|
|
1648
|
+
capture_response_body: bool = False,
|
|
1649
|
+
request_hook: HttpxRequestHook | HttpxAsyncRequestHook | None = None,
|
|
1650
|
+
response_hook: HttpxResponseHook | HttpxAsyncResponseHook | None = None,
|
|
1651
|
+
async_request_hook: HttpxAsyncRequestHook | None = None,
|
|
1652
|
+
async_response_hook: HttpxAsyncResponseHook | None = None,
|
|
1653
|
+
**kwargs: Any,
|
|
1654
|
+
) -> None:
|
|
1655
|
+
"""Instrument the `httpx` and `httpx2` modules so that spans are automatically created for each request.
|
|
1656
|
+
|
|
1657
|
+
Optionally, pass an `httpx` or `httpx2` client instance to instrument only that client.
|
|
1658
|
+
|
|
1659
|
+
Uses the
|
|
1660
|
+
[OpenTelemetry HTTPX Instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/httpx/httpx.html)
|
|
1661
|
+
library, specifically `HTTPXClientInstrumentor().instrument()` (or `HTTPX2ClientInstrumentor` for `httpx2`),
|
|
1662
|
+
to which it passes `**kwargs`.
|
|
1663
|
+
|
|
1664
|
+
Args:
|
|
1665
|
+
client: The `httpx` or `httpx2` client instance to instrument.
|
|
1666
|
+
If `None`, the default, all clients from both installed libraries will be instrumented.
|
|
1667
|
+
capture_all: Set to `True` to capture all HTTP headers, request and response bodies.
|
|
1668
|
+
By default checks the environment variable `LOGFIRE_HTTPX_CAPTURE_ALL`.
|
|
1669
|
+
capture_headers: Set to `True` to capture all HTTP headers.
|
|
1670
|
+
|
|
1671
|
+
If you don't want to capture all headers, you can customize the headers captured. See the
|
|
1672
|
+
[Capture Headers](https://logfire.pydantic.dev/docs/guides/advanced/capture_headers/) section for more info.
|
|
1673
|
+
capture_request_body: Set to `True` to capture the request body.
|
|
1674
|
+
capture_response_body: Set to `True` to capture the response body.
|
|
1675
|
+
request_hook: A function called right after a span is created for a request.
|
|
1676
|
+
response_hook: A function called right before a span is finished for the response.
|
|
1677
|
+
async_request_hook: A function called right after a span is created for an async request.
|
|
1678
|
+
async_response_hook: A function called right before a span is finished for an async response.
|
|
1679
|
+
**kwargs: Additional keyword arguments to pass to the OpenTelemetry `instrument` method, for future compatibility.
|
|
1680
|
+
"""
|
|
1681
|
+
from .integrations.httpx import instrument_httpx
|
|
1682
|
+
|
|
1683
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
1684
|
+
return instrument_httpx(
|
|
1685
|
+
self,
|
|
1686
|
+
client,
|
|
1687
|
+
capture_all=capture_all,
|
|
1688
|
+
capture_headers=capture_headers,
|
|
1689
|
+
capture_request_body=capture_request_body,
|
|
1690
|
+
capture_response_body=capture_response_body,
|
|
1691
|
+
request_hook=request_hook,
|
|
1692
|
+
response_hook=response_hook,
|
|
1693
|
+
async_request_hook=async_request_hook,
|
|
1694
|
+
async_response_hook=async_response_hook,
|
|
1695
|
+
**kwargs,
|
|
1696
|
+
)
|
|
1697
|
+
|
|
1698
|
+
def instrument_celery(self, **kwargs: Any) -> None:
|
|
1699
|
+
"""Instrument `celery` so that spans are automatically created for each task.
|
|
1700
|
+
|
|
1701
|
+
Uses the
|
|
1702
|
+
[OpenTelemetry Celery Instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/celery/celery.html)
|
|
1703
|
+
library.
|
|
1704
|
+
|
|
1705
|
+
For distributed tracing to work correctly, this must be called in **both** the worker processes
|
|
1706
|
+
and the application that enqueues tasks (e.g., your Django or FastAPI web server).
|
|
1707
|
+
See the [distributed tracing guide](https://logfire.pydantic.dev/docs/how-to-guides/distributed-tracing/#integrations).
|
|
1708
|
+
|
|
1709
|
+
See the [Celery guide](https://logfire.pydantic.dev/docs/integrations/celery/) for more details.
|
|
1710
|
+
|
|
1711
|
+
Args:
|
|
1712
|
+
**kwargs: Additional keyword arguments to pass to the OpenTelemetry `instrument` method, for future compatibility.
|
|
1713
|
+
"""
|
|
1714
|
+
from .integrations.celery import instrument_celery
|
|
1715
|
+
|
|
1716
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
1717
|
+
return instrument_celery(
|
|
1718
|
+
**{
|
|
1719
|
+
'tracer_provider': self._config.get_tracer_provider(),
|
|
1720
|
+
'meter_provider': self._config.get_meter_provider(),
|
|
1721
|
+
**kwargs,
|
|
1722
|
+
},
|
|
1723
|
+
)
|
|
1724
|
+
|
|
1725
|
+
def instrument_django(
|
|
1726
|
+
self,
|
|
1727
|
+
capture_headers: bool = False,
|
|
1728
|
+
is_sql_commentor_enabled: bool | None = None,
|
|
1729
|
+
request_hook: Callable[[trace_api.Span, HttpRequest], None] | None = None,
|
|
1730
|
+
response_hook: Callable[[trace_api.Span, HttpRequest, HttpResponse], None] | None = None,
|
|
1731
|
+
excluded_urls: str | None = None,
|
|
1732
|
+
**kwargs: Any,
|
|
1733
|
+
) -> None:
|
|
1734
|
+
"""Instrument `django` so that spans are automatically created for each web request.
|
|
1735
|
+
|
|
1736
|
+
Uses the
|
|
1737
|
+
[OpenTelemetry Django Instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/django/django.html)
|
|
1738
|
+
library.
|
|
1739
|
+
|
|
1740
|
+
Args:
|
|
1741
|
+
capture_headers: Set to `True` to capture all request and response headers.
|
|
1742
|
+
is_sql_commentor_enabled: Adds comments to SQL queries performed by Django,
|
|
1743
|
+
so that database logs have additional context.
|
|
1744
|
+
|
|
1745
|
+
This does NOT create spans/logs for the queries themselves.
|
|
1746
|
+
For that you need to instrument the database driver, e.g. with `logfire.instrument_psycopg()`.
|
|
1747
|
+
|
|
1748
|
+
To configure the SQL Commentor, see the OpenTelemetry documentation for the
|
|
1749
|
+
values that need to be added to `settings.py`.
|
|
1750
|
+
|
|
1751
|
+
request_hook: A function called right after a span is created for a request.
|
|
1752
|
+
The function should accept two arguments: the span and the Django `Request` object.
|
|
1753
|
+
|
|
1754
|
+
response_hook: A function called right before a span is finished for the response.
|
|
1755
|
+
The function should accept three arguments:
|
|
1756
|
+
the span, the Django `Request` object, and the Django `Response` object.
|
|
1757
|
+
|
|
1758
|
+
excluded_urls: A string containing a comma-delimited list of regexes used to exclude URLs from tracking.
|
|
1759
|
+
|
|
1760
|
+
**kwargs: Additional keyword arguments to pass to the OpenTelemetry `instrument` method,
|
|
1761
|
+
for future compatibility.
|
|
1762
|
+
|
|
1763
|
+
"""
|
|
1764
|
+
from .integrations.django import instrument_django
|
|
1765
|
+
|
|
1766
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
1767
|
+
return instrument_django(
|
|
1768
|
+
capture_headers=capture_headers,
|
|
1769
|
+
is_sql_commentor_enabled=is_sql_commentor_enabled,
|
|
1770
|
+
request_hook=request_hook,
|
|
1771
|
+
response_hook=response_hook,
|
|
1772
|
+
excluded_urls=excluded_urls,
|
|
1773
|
+
**{
|
|
1774
|
+
'tracer_provider': self._config.get_tracer_provider(),
|
|
1775
|
+
'meter_provider': self._config.get_meter_provider(),
|
|
1776
|
+
**kwargs,
|
|
1777
|
+
},
|
|
1778
|
+
)
|
|
1779
|
+
|
|
1780
|
+
def instrument_requests(
|
|
1781
|
+
self,
|
|
1782
|
+
excluded_urls: str | None = None,
|
|
1783
|
+
request_hook: Callable[[Span, requests.PreparedRequest], None] | None = None,
|
|
1784
|
+
response_hook: Callable[[Span, requests.PreparedRequest, requests.Response], None] | None = None,
|
|
1785
|
+
**kwargs: Any,
|
|
1786
|
+
) -> None:
|
|
1787
|
+
"""Instrument the `requests` module so that spans are automatically created for each request.
|
|
1788
|
+
|
|
1789
|
+
Args:
|
|
1790
|
+
excluded_urls: A string containing a comma-delimited list of regexes used to exclude URLs from tracking
|
|
1791
|
+
request_hook: A function called right after a span is created for a request.
|
|
1792
|
+
response_hook: A function called right before a span is finished for the response.
|
|
1793
|
+
**kwargs: Additional keyword arguments to pass to the OpenTelemetry `instrument` methods, for future compatibility.
|
|
1794
|
+
"""
|
|
1795
|
+
from .integrations.requests import instrument_requests
|
|
1796
|
+
|
|
1797
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
1798
|
+
return instrument_requests(
|
|
1799
|
+
excluded_urls=excluded_urls,
|
|
1800
|
+
request_hook=request_hook,
|
|
1801
|
+
response_hook=response_hook,
|
|
1802
|
+
**{
|
|
1803
|
+
'tracer_provider': self._config.get_tracer_provider(),
|
|
1804
|
+
'meter_provider': self._config.get_meter_provider(),
|
|
1805
|
+
**kwargs,
|
|
1806
|
+
},
|
|
1807
|
+
)
|
|
1808
|
+
|
|
1809
|
+
@overload
|
|
1810
|
+
def instrument_psycopg(self, conn_or_module: PsycopgConnection | Psycopg2Connection, **kwargs: Any) -> None: ...
|
|
1811
|
+
|
|
1812
|
+
@overload
|
|
1813
|
+
def instrument_psycopg(
|
|
1814
|
+
self,
|
|
1815
|
+
conn_or_module: None | Literal['psycopg', 'psycopg2'] | ModuleType = None,
|
|
1816
|
+
enable_commenter: bool = False,
|
|
1817
|
+
commenter_options: PsycopgCommenterOptions | None = None,
|
|
1818
|
+
**kwargs: Any,
|
|
1819
|
+
) -> None: ...
|
|
1820
|
+
|
|
1821
|
+
def instrument_psycopg(
|
|
1822
|
+
self,
|
|
1823
|
+
conn_or_module: Any = None,
|
|
1824
|
+
enable_commenter: bool = False,
|
|
1825
|
+
commenter_options: PsycopgCommenterOptions | None = None,
|
|
1826
|
+
**kwargs: Any,
|
|
1827
|
+
) -> None:
|
|
1828
|
+
"""Instrument a `psycopg` connection or module so that spans are automatically created for each query.
|
|
1829
|
+
|
|
1830
|
+
Uses the OpenTelemetry instrumentation libraries for
|
|
1831
|
+
[`psycopg`](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/psycopg/psycopg.html)
|
|
1832
|
+
and
|
|
1833
|
+
[`psycopg2`](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/psycopg2/psycopg2.html).
|
|
1834
|
+
|
|
1835
|
+
Args:
|
|
1836
|
+
conn_or_module: Can be:
|
|
1837
|
+
|
|
1838
|
+
- The `psycopg` (version 3) or `psycopg2` module.
|
|
1839
|
+
- The string `'psycopg'` or `'psycopg2'` to instrument the module.
|
|
1840
|
+
- `None` (the default) to instrument whichever module(s) are installed.
|
|
1841
|
+
- A `psycopg` or `psycopg2` connection.
|
|
1842
|
+
|
|
1843
|
+
enable_commenter: Adds comments to SQL queries performed by Psycopg, so that database logs have additional context.
|
|
1844
|
+
commenter_options: Configure the tags to be added to the SQL comments.
|
|
1845
|
+
**kwargs: Additional keyword arguments to pass to the OpenTelemetry `instrument` methods,
|
|
1846
|
+
for future compatibility.
|
|
1847
|
+
"""
|
|
1848
|
+
from .integrations.psycopg import instrument_psycopg
|
|
1849
|
+
|
|
1850
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
1851
|
+
if enable_commenter:
|
|
1852
|
+
kwargs.update({'enable_commenter': True, 'commenter_options': commenter_options or {}})
|
|
1853
|
+
return instrument_psycopg(self, conn_or_module=conn_or_module, **kwargs)
|
|
1854
|
+
|
|
1855
|
+
def instrument_flask(
|
|
1856
|
+
self,
|
|
1857
|
+
app: Flask,
|
|
1858
|
+
*,
|
|
1859
|
+
capture_headers: bool = False,
|
|
1860
|
+
enable_commenter: bool = True,
|
|
1861
|
+
commenter_options: FlaskCommenterOptions | None = None,
|
|
1862
|
+
excluded_urls: str | None = None,
|
|
1863
|
+
request_hook: FlaskRequestHook | None = None,
|
|
1864
|
+
response_hook: FlaskResponseHook | None = None,
|
|
1865
|
+
**kwargs: Any,
|
|
1866
|
+
) -> None:
|
|
1867
|
+
"""Instrument `app` so that spans are automatically created for each request.
|
|
1868
|
+
|
|
1869
|
+
Uses the
|
|
1870
|
+
[OpenTelemetry Flask Instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/flask/flask.html)
|
|
1871
|
+
library, specifically `FlaskInstrumentor().instrument_app()`, to which it passes `**kwargs`.
|
|
1872
|
+
|
|
1873
|
+
Args:
|
|
1874
|
+
app: The Flask app to instrument.
|
|
1875
|
+
capture_headers: Set to `True` to capture all request and response headers.
|
|
1876
|
+
enable_commenter: Adds comments to SQL queries performed by Flask, so that database logs have additional context.
|
|
1877
|
+
commenter_options: Configure the tags to be added to the SQL comments.
|
|
1878
|
+
See more about it on the [SQLCommenter Configurations](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/flask/flask.html#sqlcommenter-configurations).
|
|
1879
|
+
excluded_urls: A string containing a comma-delimited list of regexes used to exclude URLs from tracking.
|
|
1880
|
+
request_hook: A function called right after a span is created for a request.
|
|
1881
|
+
response_hook: A function called right before a span is finished for the response.
|
|
1882
|
+
**kwargs: Additional keyword arguments to pass to the OpenTelemetry Flask instrumentation.
|
|
1883
|
+
"""
|
|
1884
|
+
from .integrations.flask import instrument_flask
|
|
1885
|
+
|
|
1886
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
1887
|
+
return instrument_flask(
|
|
1888
|
+
self,
|
|
1889
|
+
app,
|
|
1890
|
+
capture_headers=capture_headers,
|
|
1891
|
+
enable_commenter=enable_commenter,
|
|
1892
|
+
commenter_options=commenter_options,
|
|
1893
|
+
excluded_urls=excluded_urls,
|
|
1894
|
+
request_hook=request_hook,
|
|
1895
|
+
response_hook=response_hook,
|
|
1896
|
+
**kwargs,
|
|
1897
|
+
)
|
|
1898
|
+
|
|
1899
|
+
def instrument_litestar(
|
|
1900
|
+
self,
|
|
1901
|
+
app: Litestar,
|
|
1902
|
+
*,
|
|
1903
|
+
capture_headers: bool = False,
|
|
1904
|
+
record_send_receive: bool = False,
|
|
1905
|
+
**kwargs: Unpack[ASGIInstrumentKwargs],
|
|
1906
|
+
) -> ASGIApp:
|
|
1907
|
+
"""Instrument a Litestar app to record requests with canonical route templates.
|
|
1908
|
+
|
|
1909
|
+
Uses `instrument_asgi()` with a Litestar route extractor, so requests to
|
|
1910
|
+
`/users/1` and `/users/2` share the route `/users/{user_id}`.
|
|
1911
|
+
|
|
1912
|
+
Warning:
|
|
1913
|
+
This method returns an ASGI wrapper instead of modifying the app in place.
|
|
1914
|
+
Pass the returned app to your server. Access Litestar-specific attributes
|
|
1915
|
+
through the original app.
|
|
1916
|
+
|
|
1917
|
+
Args:
|
|
1918
|
+
app: The Litestar app to instrument.
|
|
1919
|
+
capture_headers: Set to `True` to capture all request and response headers.
|
|
1920
|
+
record_send_receive: Set to `True` to record low-level ASGI send and receive spans.
|
|
1921
|
+
These are disabled by default to reduce noise.
|
|
1922
|
+
**kwargs: Additional options for the OpenTelemetry ASGI middleware, including
|
|
1923
|
+
`server_request_hook`, `client_request_hook`, `client_response_hook`,
|
|
1924
|
+
`excluded_urls`, and `default_span_details`.
|
|
1925
|
+
|
|
1926
|
+
Returns:
|
|
1927
|
+
The instrumented ASGI application.
|
|
1928
|
+
"""
|
|
1929
|
+
from .integrations.litestar import instrument_litestar
|
|
1930
|
+
|
|
1931
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
1932
|
+
return instrument_litestar(
|
|
1933
|
+
self,
|
|
1934
|
+
app,
|
|
1935
|
+
capture_headers=capture_headers,
|
|
1936
|
+
record_send_receive=record_send_receive,
|
|
1937
|
+
**kwargs,
|
|
1938
|
+
)
|
|
1939
|
+
|
|
1940
|
+
def instrument_starlette(
|
|
1941
|
+
self,
|
|
1942
|
+
app: Starlette,
|
|
1943
|
+
*,
|
|
1944
|
+
capture_headers: bool = False,
|
|
1945
|
+
record_send_receive: bool = False,
|
|
1946
|
+
server_request_hook: ServerRequestHook | None = None,
|
|
1947
|
+
client_request_hook: ClientRequestHook | None = None,
|
|
1948
|
+
client_response_hook: ClientResponseHook | None = None,
|
|
1949
|
+
**kwargs: Any,
|
|
1950
|
+
) -> None:
|
|
1951
|
+
"""Instrument `app` so that spans are automatically created for each request.
|
|
1952
|
+
|
|
1953
|
+
Uses the
|
|
1954
|
+
[OpenTelemetry Starlette Instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/starlette/starlette.html)
|
|
1955
|
+
library, specifically `StarletteInstrumentor.instrument_app()`, to which it passes `**kwargs`.
|
|
1956
|
+
|
|
1957
|
+
Args:
|
|
1958
|
+
app: The Starlette app to instrument.
|
|
1959
|
+
capture_headers: Set to `True` to capture all request and response headers.
|
|
1960
|
+
record_send_receive: Set to `True` to allow the OpenTelemetry ASGI middleware to create send/receive spans.
|
|
1961
|
+
|
|
1962
|
+
These are disabled by default to reduce overhead and the number of spans created,
|
|
1963
|
+
since many can be created for a single request, and they are not often useful.
|
|
1964
|
+
If enabled, they will be set to debug level, meaning they will usually still be hidden in the UI.
|
|
1965
|
+
server_request_hook: A function that receives a server span and the ASGI scope for every incoming request.
|
|
1966
|
+
client_request_hook: A function that receives a span, the ASGI scope and the receive ASGI message for every ASGI receive event.
|
|
1967
|
+
client_response_hook: A function that receives a span, the ASGI scope and the send ASGI message for every ASGI send event.
|
|
1968
|
+
**kwargs: Additional keyword arguments to pass to the OpenTelemetry Starlette instrumentation.
|
|
1969
|
+
"""
|
|
1970
|
+
from .integrations.starlette import instrument_starlette
|
|
1971
|
+
|
|
1972
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
1973
|
+
return instrument_starlette(
|
|
1974
|
+
self,
|
|
1975
|
+
app,
|
|
1976
|
+
record_send_receive=record_send_receive,
|
|
1977
|
+
capture_headers=capture_headers,
|
|
1978
|
+
server_request_hook=server_request_hook,
|
|
1979
|
+
client_request_hook=client_request_hook,
|
|
1980
|
+
client_response_hook=client_response_hook,
|
|
1981
|
+
**kwargs,
|
|
1982
|
+
)
|
|
1983
|
+
|
|
1984
|
+
def instrument_asgi(
|
|
1985
|
+
self,
|
|
1986
|
+
app: ASGIApp,
|
|
1987
|
+
capture_headers: bool = False,
|
|
1988
|
+
record_send_receive: bool = False,
|
|
1989
|
+
**kwargs: Unpack[ASGIInstrumentKwargs],
|
|
1990
|
+
) -> ASGIApp:
|
|
1991
|
+
"""Instrument `app` so that spans are automatically created for each request.
|
|
1992
|
+
|
|
1993
|
+
Uses the ASGI [`OpenTelemetryMiddleware`][opentelemetry.instrumentation.asgi.OpenTelemetryMiddleware] under
|
|
1994
|
+
the hood, to which it passes `**kwargs`.
|
|
1995
|
+
|
|
1996
|
+
Warning:
|
|
1997
|
+
Instead of modifying the app in place, this method returns the instrumented ASGI application.
|
|
1998
|
+
|
|
1999
|
+
Args:
|
|
2000
|
+
app: The ASGI application to instrument.
|
|
2001
|
+
capture_headers: Set to `True` to capture all request and response headers.
|
|
2002
|
+
record_send_receive: Set to `True` to allow the OpenTelemetry ASGI middleware to create send/receive spans.
|
|
2003
|
+
|
|
2004
|
+
These are disabled by default to reduce overhead and the number of spans created,
|
|
2005
|
+
since many can be created for a single request, and they are not often useful.
|
|
2006
|
+
If enabled, they will be set to debug level, meaning they will usually still be hidden in the UI.
|
|
2007
|
+
**kwargs: Additional keyword arguments to pass to the OpenTelemetry ASGI middleware.
|
|
2008
|
+
|
|
2009
|
+
Returns:
|
|
2010
|
+
The instrumented ASGI application.
|
|
2011
|
+
"""
|
|
2012
|
+
from .integrations.asgi import instrument_asgi
|
|
2013
|
+
|
|
2014
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
2015
|
+
return instrument_asgi(
|
|
2016
|
+
self,
|
|
2017
|
+
app,
|
|
2018
|
+
record_send_receive=record_send_receive,
|
|
2019
|
+
capture_headers=capture_headers,
|
|
2020
|
+
**kwargs,
|
|
2021
|
+
)
|
|
2022
|
+
|
|
2023
|
+
def instrument_wsgi(
|
|
2024
|
+
self,
|
|
2025
|
+
app: WSGIApplication,
|
|
2026
|
+
capture_headers: bool = False,
|
|
2027
|
+
request_hook: WSGIRequestHook | None = None,
|
|
2028
|
+
response_hook: WSGIResponseHook | None = None,
|
|
2029
|
+
**kwargs: Any,
|
|
2030
|
+
) -> WSGIApplication:
|
|
2031
|
+
"""Instrument `app` so that spans are automatically created for each request.
|
|
2032
|
+
|
|
2033
|
+
Uses the WSGI [`OpenTelemetryMiddleware`][opentelemetry.instrumentation.wsgi.OpenTelemetryMiddleware] under
|
|
2034
|
+
the hood, to which it passes `**kwargs`.
|
|
2035
|
+
|
|
2036
|
+
Warning:
|
|
2037
|
+
Instead of modifying the app in place, this method returns the instrumented WSGI application.
|
|
2038
|
+
|
|
2039
|
+
Args:
|
|
2040
|
+
app: The WSGI application to instrument.
|
|
2041
|
+
capture_headers: Set to `True` to capture all request and response headers.
|
|
2042
|
+
request_hook: A function called right after a span is created for a request.
|
|
2043
|
+
response_hook: A function called right before a span is finished for the response.
|
|
2044
|
+
**kwargs: Additional keyword arguments to pass to the OpenTelemetry WSGI middleware.
|
|
2045
|
+
|
|
2046
|
+
Returns:
|
|
2047
|
+
The instrumented WSGI application.
|
|
2048
|
+
"""
|
|
2049
|
+
from .integrations.wsgi import instrument_wsgi
|
|
2050
|
+
|
|
2051
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
2052
|
+
return instrument_wsgi(
|
|
2053
|
+
app,
|
|
2054
|
+
capture_headers=capture_headers,
|
|
2055
|
+
request_hook=request_hook,
|
|
2056
|
+
response_hook=response_hook,
|
|
2057
|
+
**{
|
|
2058
|
+
'tracer_provider': self._config.get_tracer_provider(),
|
|
2059
|
+
'meter_provider': self._config.get_meter_provider(),
|
|
2060
|
+
**kwargs,
|
|
2061
|
+
},
|
|
2062
|
+
)
|
|
2063
|
+
|
|
2064
|
+
def instrument_aiohttp_client(
|
|
2065
|
+
self,
|
|
2066
|
+
*,
|
|
2067
|
+
capture_all: bool | None = None,
|
|
2068
|
+
capture_headers: bool = False,
|
|
2069
|
+
capture_request_body: bool = False,
|
|
2070
|
+
capture_response_body: bool = False,
|
|
2071
|
+
request_hook: AiohttpClientRequestHook | None = None,
|
|
2072
|
+
response_hook: AiohttpClientResponseHook | None = None,
|
|
2073
|
+
**kwargs: Any,
|
|
2074
|
+
) -> None:
|
|
2075
|
+
"""Instrument the `aiohttp` module so that spans are automatically created for each client request.
|
|
2076
|
+
|
|
2077
|
+
Uses the
|
|
2078
|
+
[OpenTelemetry aiohttp client Instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/aiohttp_client/aiohttp_client.html)
|
|
2079
|
+
library, specifically `AioHttpClientInstrumentor().instrument()`, to which it passes `**kwargs`.
|
|
2080
|
+
"""
|
|
2081
|
+
from .integrations.aiohttp_client import instrument_aiohttp_client
|
|
2082
|
+
|
|
2083
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
2084
|
+
return instrument_aiohttp_client(
|
|
2085
|
+
self,
|
|
2086
|
+
capture_all=capture_all,
|
|
2087
|
+
capture_request_body=capture_request_body,
|
|
2088
|
+
capture_response_body=capture_response_body,
|
|
2089
|
+
capture_headers=capture_headers,
|
|
2090
|
+
request_hook=request_hook,
|
|
2091
|
+
response_hook=response_hook,
|
|
2092
|
+
**kwargs,
|
|
2093
|
+
)
|
|
2094
|
+
|
|
2095
|
+
def instrument_aiohttp_server(self, **kwargs: Any) -> None:
|
|
2096
|
+
"""Instrument the `aiohttp` module so that spans are automatically created for each server request.
|
|
2097
|
+
|
|
2098
|
+
Uses the
|
|
2099
|
+
[OpenTelemetry aiohttp server Instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/aiohttp_server/aiohttp_server.html)
|
|
2100
|
+
library, specifically `AioHttpServerInstrumentor().instrument()`, to which it passes `**kwargs`.
|
|
2101
|
+
"""
|
|
2102
|
+
from .integrations.aiohttp_server import instrument_aiohttp_server
|
|
2103
|
+
|
|
2104
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
2105
|
+
return instrument_aiohttp_server(
|
|
2106
|
+
**{
|
|
2107
|
+
'tracer_provider': self._config.get_tracer_provider(),
|
|
2108
|
+
'meter_provider': self._config.get_meter_provider(),
|
|
2109
|
+
**kwargs,
|
|
2110
|
+
},
|
|
2111
|
+
)
|
|
2112
|
+
|
|
2113
|
+
def instrument_sqlalchemy(
|
|
2114
|
+
self,
|
|
2115
|
+
engine: AsyncEngine | Engine | None = None,
|
|
2116
|
+
engines: Iterable[AsyncEngine | Engine] | None = None,
|
|
2117
|
+
enable_commenter: bool = False,
|
|
2118
|
+
commenter_options: SQLAlchemyCommenterOptions | None = None,
|
|
2119
|
+
**kwargs: Any,
|
|
2120
|
+
) -> None:
|
|
2121
|
+
"""Instrument the `sqlalchemy` module so that spans are automatically created for each query.
|
|
2122
|
+
|
|
2123
|
+
Uses the
|
|
2124
|
+
[OpenTelemetry SQLAlchemy Instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/sqlalchemy/sqlalchemy.html)
|
|
2125
|
+
library, specifically `SQLAlchemyInstrumentor().instrument()`, to which it passes `**kwargs`.
|
|
2126
|
+
|
|
2127
|
+
If the installed SQLAlchemy version is outside the range that instrumentation supports, this raises
|
|
2128
|
+
`RuntimeError` instead of returning without recording queries.
|
|
2129
|
+
Pass `skip_dep_check=True` to bypass this check. That may produce no spans or errors if the version really is incompatible.
|
|
2130
|
+
|
|
2131
|
+
Args:
|
|
2132
|
+
engine: The `sqlalchemy` engine to instrument.
|
|
2133
|
+
engines: An iterable of `sqlalchemy` engines to instrument.
|
|
2134
|
+
enable_commenter: Adds comments to SQL queries performed by SQLAlchemy, so that database logs have additional context.
|
|
2135
|
+
commenter_options: Configure the tags to be added to the SQL comments.
|
|
2136
|
+
**kwargs: Additional keyword arguments to pass to the OpenTelemetry `instrument` methods.
|
|
2137
|
+
"""
|
|
2138
|
+
from .integrations.sqlalchemy import instrument_sqlalchemy
|
|
2139
|
+
|
|
2140
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
2141
|
+
return instrument_sqlalchemy(
|
|
2142
|
+
engine=engine,
|
|
2143
|
+
engines=engines,
|
|
2144
|
+
enable_commenter=enable_commenter,
|
|
2145
|
+
commenter_options=commenter_options or {},
|
|
2146
|
+
**{
|
|
2147
|
+
'tracer_provider': self._config.get_tracer_provider(),
|
|
2148
|
+
'meter_provider': self._config.get_meter_provider(),
|
|
2149
|
+
**kwargs,
|
|
2150
|
+
},
|
|
2151
|
+
)
|
|
2152
|
+
|
|
2153
|
+
def instrument_sqlite3(self, conn: SQLite3Connection = None, **kwargs: Any) -> SQLite3Connection:
|
|
2154
|
+
"""Instrument the `sqlite3` module or a specific connection so that spans are automatically created for each operation.
|
|
2155
|
+
|
|
2156
|
+
Uses the
|
|
2157
|
+
[OpenTelemetry SQLite3 Instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/sqlite3/sqlite3.html)
|
|
2158
|
+
library.
|
|
2159
|
+
|
|
2160
|
+
Args:
|
|
2161
|
+
conn: The `sqlite3` connection to instrument, or `None` to instrument all connections.
|
|
2162
|
+
**kwargs: Additional keyword arguments to pass to the OpenTelemetry `instrument` methods.
|
|
2163
|
+
|
|
2164
|
+
Returns:
|
|
2165
|
+
If a connection is provided, returns the instrumented connection. If no connection is provided, returns `None`.
|
|
2166
|
+
"""
|
|
2167
|
+
from .integrations.sqlite3 import instrument_sqlite3
|
|
2168
|
+
|
|
2169
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
2170
|
+
return instrument_sqlite3(conn=conn, **{'tracer_provider': self._config.get_tracer_provider(), **kwargs})
|
|
2171
|
+
|
|
2172
|
+
def instrument_aws_lambda(
|
|
2173
|
+
self,
|
|
2174
|
+
lambda_handler: LambdaHandler,
|
|
2175
|
+
event_context_extractor: Callable[[LambdaEvent], Context] | None = None,
|
|
2176
|
+
**kwargs: Any,
|
|
2177
|
+
) -> None:
|
|
2178
|
+
"""Instrument AWS Lambda so that spans are automatically created for each invocation.
|
|
2179
|
+
|
|
2180
|
+
Uses the
|
|
2181
|
+
[OpenTelemetry AWS Lambda Instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/aws_lambda/aws_lambda.html)
|
|
2182
|
+
library, specifically `AwsLambdaInstrumentor().instrument()`, to which it passes `**kwargs`.
|
|
2183
|
+
|
|
2184
|
+
Args:
|
|
2185
|
+
lambda_handler: The lambda handler function to instrument.
|
|
2186
|
+
event_context_extractor: A function that returns an OTel Trace Context given the Lambda Event the AWS.
|
|
2187
|
+
**kwargs: Additional keyword arguments to pass to the OpenTelemetry `instrument` methods for future compatibility.
|
|
2188
|
+
"""
|
|
2189
|
+
from .integrations.aws_lambda import instrument_aws_lambda
|
|
2190
|
+
|
|
2191
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
2192
|
+
return instrument_aws_lambda(
|
|
2193
|
+
lambda_handler=lambda_handler,
|
|
2194
|
+
event_context_extractor=event_context_extractor,
|
|
2195
|
+
**{ # pyright: ignore[reportArgumentType]
|
|
2196
|
+
'tracer_provider': self._config.get_tracer_provider(),
|
|
2197
|
+
'meter_provider': self._config.get_meter_provider(),
|
|
2198
|
+
**kwargs,
|
|
2199
|
+
},
|
|
2200
|
+
)
|
|
2201
|
+
|
|
2202
|
+
def instrument_pymongo(
|
|
2203
|
+
self,
|
|
2204
|
+
capture_statement: bool = False,
|
|
2205
|
+
request_hook: Callable[[Span, CommandStartedEvent], None] | None = None,
|
|
2206
|
+
response_hook: Callable[[Span, CommandSucceededEvent], None] | None = None,
|
|
2207
|
+
failed_hook: Callable[[Span, CommandFailedEvent], None] | None = None,
|
|
2208
|
+
**kwargs: Any,
|
|
2209
|
+
) -> None:
|
|
2210
|
+
"""Instrument the `pymongo` module so that spans are automatically created for each operation.
|
|
2211
|
+
|
|
2212
|
+
Uses the
|
|
2213
|
+
[OpenTelemetry pymongo Instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/pymongo/pymongo.html)
|
|
2214
|
+
library, specifically `PymongoInstrumentor().instrument()`, to which it passes `**kwargs`.
|
|
2215
|
+
|
|
2216
|
+
Args:
|
|
2217
|
+
capture_statement: Set to `True` to capture the statement in the span attributes.
|
|
2218
|
+
request_hook: A function called when a command is sent to the server.
|
|
2219
|
+
response_hook: A function that is called when a command is successfully completed.
|
|
2220
|
+
failed_hook: A function that is called when a command fails.
|
|
2221
|
+
**kwargs: Additional keyword arguments to pass to the OpenTelemetry `instrument` methods for future compatibility.
|
|
2222
|
+
"""
|
|
2223
|
+
from .integrations.pymongo import instrument_pymongo
|
|
2224
|
+
|
|
2225
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
2226
|
+
return instrument_pymongo(
|
|
2227
|
+
capture_statement=capture_statement,
|
|
2228
|
+
request_hook=request_hook,
|
|
2229
|
+
response_hook=response_hook,
|
|
2230
|
+
failed_hook=failed_hook,
|
|
2231
|
+
**{
|
|
2232
|
+
'tracer_provider': self._config.get_tracer_provider(),
|
|
2233
|
+
'meter_provider': self._config.get_meter_provider(),
|
|
2234
|
+
**kwargs,
|
|
2235
|
+
},
|
|
2236
|
+
)
|
|
2237
|
+
|
|
2238
|
+
def instrument_redis(
|
|
2239
|
+
self,
|
|
2240
|
+
capture_statement: bool = False,
|
|
2241
|
+
request_hook: RedisRequestHook | None = None,
|
|
2242
|
+
response_hook: RedisResponseHook | None = None,
|
|
2243
|
+
**kwargs: Any,
|
|
2244
|
+
) -> None:
|
|
2245
|
+
"""Instrument the `redis` module so that spans are automatically created for each operation.
|
|
2246
|
+
|
|
2247
|
+
Uses the
|
|
2248
|
+
[OpenTelemetry Redis Instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/redis/redis.html)
|
|
2249
|
+
library, specifically `RedisInstrumentor().instrument()`, to which it passes `**kwargs`.
|
|
2250
|
+
|
|
2251
|
+
Args:
|
|
2252
|
+
capture_statement: Set to `True` to capture the statement in the span attributes.
|
|
2253
|
+
request_hook: A function that is called before performing the request.
|
|
2254
|
+
response_hook: A function that is called after receiving the response.
|
|
2255
|
+
**kwargs: Additional keyword arguments to pass to the OpenTelemetry `instrument` methods for future compatibility.
|
|
2256
|
+
"""
|
|
2257
|
+
from .integrations.redis import instrument_redis
|
|
2258
|
+
|
|
2259
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
2260
|
+
return instrument_redis(
|
|
2261
|
+
capture_statement=capture_statement,
|
|
2262
|
+
request_hook=request_hook,
|
|
2263
|
+
response_hook=response_hook,
|
|
2264
|
+
**{
|
|
2265
|
+
'tracer_provider': self._config.get_tracer_provider(),
|
|
2266
|
+
'meter_provider': self._config.get_meter_provider(),
|
|
2267
|
+
**kwargs,
|
|
2268
|
+
},
|
|
2269
|
+
)
|
|
2270
|
+
|
|
2271
|
+
def instrument_mysql(self, conn: MySQLConnection = None, **kwargs: Any) -> MySQLConnection:
|
|
2272
|
+
"""Instrument the `mysql` module or a specific MySQL connection so that spans are automatically created for each operation.
|
|
2273
|
+
|
|
2274
|
+
Uses the
|
|
2275
|
+
[OpenTelemetry MySQL Instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/mysql/mysql.html)
|
|
2276
|
+
library.
|
|
2277
|
+
|
|
2278
|
+
Args:
|
|
2279
|
+
conn: The `mysql` connection to instrument, or `None` to instrument all connections.
|
|
2280
|
+
**kwargs: Additional keyword arguments to pass to the OpenTelemetry `instrument` methods.
|
|
2281
|
+
|
|
2282
|
+
Returns:
|
|
2283
|
+
If a connection is provided, returns the instrumented connection. If no connection is provided, returns None.
|
|
2284
|
+
"""
|
|
2285
|
+
from .integrations.mysql import instrument_mysql
|
|
2286
|
+
|
|
2287
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
2288
|
+
return instrument_mysql(
|
|
2289
|
+
conn=conn,
|
|
2290
|
+
**{ # pyright: ignore[reportArgumentType]
|
|
2291
|
+
'tracer_provider': self._config.get_tracer_provider(),
|
|
2292
|
+
'meter_provider': self._config.get_meter_provider(),
|
|
2293
|
+
**kwargs,
|
|
2294
|
+
},
|
|
2295
|
+
)
|
|
2296
|
+
|
|
2297
|
+
def instrument_system_metrics(
|
|
2298
|
+
self, config: SystemMetricsConfig | None = None, base: SystemMetricsBase = 'basic'
|
|
2299
|
+
) -> None:
|
|
2300
|
+
"""Collect system metrics.
|
|
2301
|
+
|
|
2302
|
+
See [the guide](https://logfire.pydantic.dev/docs/integrations/system-metrics/) for more information.
|
|
2303
|
+
|
|
2304
|
+
Args:
|
|
2305
|
+
config: A dictionary where the keys are metric names
|
|
2306
|
+
and the values are optional further configuration for that metric.
|
|
2307
|
+
base: A string indicating the base config dictionary which `config` will be merged with,
|
|
2308
|
+
or `None` for an empty base config.
|
|
2309
|
+
"""
|
|
2310
|
+
from .integrations.system_metrics import instrument_system_metrics
|
|
2311
|
+
|
|
2312
|
+
self._warn_if_not_initialized_for_instrumentation()
|
|
2313
|
+
return instrument_system_metrics(self, config, base)
|
|
2314
|
+
|
|
2315
|
+
def metric_counter(self, name: str, *, unit: str = '', description: str = '') -> Counter:
|
|
2316
|
+
"""Create a counter metric.
|
|
2317
|
+
|
|
2318
|
+
A counter is a cumulative metric that represents a single numerical value that only ever goes up.
|
|
2319
|
+
|
|
2320
|
+
```py
|
|
2321
|
+
import logfire
|
|
2322
|
+
|
|
2323
|
+
logfire.configure()
|
|
2324
|
+
counter = logfire.metric_counter('exceptions', unit='1', description='Number of exceptions caught')
|
|
2325
|
+
|
|
2326
|
+
try:
|
|
2327
|
+
raise Exception('oops')
|
|
2328
|
+
except Exception:
|
|
2329
|
+
counter.add(1)
|
|
2330
|
+
```
|
|
2331
|
+
|
|
2332
|
+
See the [Opentelemetry documentation](https://opentelemetry.io/docs/specs/otel/metrics/api/#counter) about
|
|
2333
|
+
counters.
|
|
2334
|
+
|
|
2335
|
+
Args:
|
|
2336
|
+
name: The name of the metric.
|
|
2337
|
+
unit: The unit of the metric.
|
|
2338
|
+
description: The description of the metric.
|
|
2339
|
+
|
|
2340
|
+
Returns:
|
|
2341
|
+
The counter metric.
|
|
2342
|
+
"""
|
|
2343
|
+
return self._meter.create_counter(name, unit, description)
|
|
2344
|
+
|
|
2345
|
+
def metric_histogram(self, name: str, *, unit: str = '', description: str = '') -> Histogram:
|
|
2346
|
+
"""Create a histogram metric.
|
|
2347
|
+
|
|
2348
|
+
A histogram is a metric that samples observations (usually things like request durations or response sizes).
|
|
2349
|
+
|
|
2350
|
+
```py
|
|
2351
|
+
import logfire
|
|
2352
|
+
|
|
2353
|
+
logfire.configure()
|
|
2354
|
+
histogram = logfire.metric_histogram('bank.amount_transferred', unit='$', description='Amount transferred')
|
|
2355
|
+
|
|
2356
|
+
|
|
2357
|
+
def transfer(amount: int):
|
|
2358
|
+
histogram.record(amount)
|
|
2359
|
+
```
|
|
2360
|
+
|
|
2361
|
+
See the [Opentelemetry documentation](https://opentelemetry.io/docs/specs/otel/metrics/api/#histogram) about
|
|
2362
|
+
|
|
2363
|
+
Args:
|
|
2364
|
+
name: The name of the metric.
|
|
2365
|
+
unit: The unit of the metric.
|
|
2366
|
+
description: The description of the metric.
|
|
2367
|
+
|
|
2368
|
+
Returns:
|
|
2369
|
+
The histogram metric.
|
|
2370
|
+
"""
|
|
2371
|
+
return self._meter.create_histogram(name, unit, description)
|
|
2372
|
+
|
|
2373
|
+
def metric_gauge(self, name: str, *, unit: str = '', description: str = '') -> Gauge:
|
|
2374
|
+
"""Create a gauge metric.
|
|
2375
|
+
|
|
2376
|
+
Gauge is a synchronous instrument which can be used to record non-additive measurements.
|
|
2377
|
+
|
|
2378
|
+
```py
|
|
2379
|
+
import logfire
|
|
2380
|
+
|
|
2381
|
+
logfire.configure()
|
|
2382
|
+
gauge = logfire.metric_gauge('system.cpu_usage', unit='%', description='CPU usage')
|
|
2383
|
+
|
|
2384
|
+
|
|
2385
|
+
def update_cpu_usage(cpu_percent):
|
|
2386
|
+
gauge.set(cpu_percent)
|
|
2387
|
+
```
|
|
2388
|
+
|
|
2389
|
+
See the [Opentelemetry documentation](https://opentelemetry.io/docs/specs/otel/metrics/api/#gauge) about gauges.
|
|
2390
|
+
|
|
2391
|
+
Args:
|
|
2392
|
+
name: The name of the metric.
|
|
2393
|
+
unit: The unit of the metric.
|
|
2394
|
+
description: The description of the metric.
|
|
2395
|
+
|
|
2396
|
+
Returns:
|
|
2397
|
+
The gauge metric.
|
|
2398
|
+
"""
|
|
2399
|
+
return self._meter.create_gauge(name, unit, description)
|
|
2400
|
+
|
|
2401
|
+
def metric_up_down_counter(self, name: str, *, unit: str = '', description: str = '') -> UpDownCounter:
|
|
2402
|
+
"""Create an up-down counter metric.
|
|
2403
|
+
|
|
2404
|
+
An up-down counter is a cumulative metric that represents a single numerical value that can be adjusted up or
|
|
2405
|
+
down.
|
|
2406
|
+
|
|
2407
|
+
```py
|
|
2408
|
+
import logfire
|
|
2409
|
+
|
|
2410
|
+
logfire.configure()
|
|
2411
|
+
up_down_counter = logfire.metric_up_down_counter('users.logged_in', unit='1', description='Users logged in')
|
|
2412
|
+
|
|
2413
|
+
|
|
2414
|
+
def on_login(user):
|
|
2415
|
+
up_down_counter.add(1)
|
|
2416
|
+
|
|
2417
|
+
|
|
2418
|
+
def on_logout(user):
|
|
2419
|
+
up_down_counter.add(-1)
|
|
2420
|
+
```
|
|
2421
|
+
|
|
2422
|
+
See the [Opentelemetry documentation](https://opentelemetry.io/docs/specs/otel/metrics/api/#updowncounter) about
|
|
2423
|
+
up-down counters.
|
|
2424
|
+
|
|
2425
|
+
Args:
|
|
2426
|
+
name: The name of the metric.
|
|
2427
|
+
unit: The unit of the metric.
|
|
2428
|
+
description: The description of the metric.
|
|
2429
|
+
|
|
2430
|
+
Returns:
|
|
2431
|
+
The up-down counter metric.
|
|
2432
|
+
"""
|
|
2433
|
+
return self._meter.create_up_down_counter(name, unit, description)
|
|
2434
|
+
|
|
2435
|
+
def metric_counter_callback(
|
|
2436
|
+
self,
|
|
2437
|
+
name: str,
|
|
2438
|
+
*,
|
|
2439
|
+
callbacks: Sequence[CallbackT],
|
|
2440
|
+
unit: str = '',
|
|
2441
|
+
description: str = '',
|
|
2442
|
+
) -> None:
|
|
2443
|
+
"""Create a counter metric that uses a callback to collect observations.
|
|
2444
|
+
|
|
2445
|
+
The callback is called every 60 seconds in a background thread.
|
|
2446
|
+
|
|
2447
|
+
The counter metric is a cumulative metric that represents a single numerical value that only ever goes up.
|
|
2448
|
+
|
|
2449
|
+
```py
|
|
2450
|
+
import psutil
|
|
2451
|
+
from opentelemetry.metrics import CallbackOptions, Observation
|
|
2452
|
+
|
|
2453
|
+
import logfire
|
|
2454
|
+
|
|
2455
|
+
logfire.configure()
|
|
2456
|
+
|
|
2457
|
+
|
|
2458
|
+
def cpu_usage_callback(options: CallbackOptions):
|
|
2459
|
+
cpu_percents = psutil.cpu_percent(percpu=True)
|
|
2460
|
+
|
|
2461
|
+
for i, cpu_percent in enumerate(cpu_percents):
|
|
2462
|
+
yield Observation(cpu_percent, {'cpu': i})
|
|
2463
|
+
|
|
2464
|
+
|
|
2465
|
+
cpu_usage_counter = logfire.metric_counter_callback(
|
|
2466
|
+
'system.cpu.usage',
|
|
2467
|
+
callbacks=[cpu_usage_callback],
|
|
2468
|
+
unit='%',
|
|
2469
|
+
description='CPU usage',
|
|
2470
|
+
)
|
|
2471
|
+
```
|
|
2472
|
+
|
|
2473
|
+
See the [Opentelemetry documentation](https://opentelemetry.io/docs/specs/otel/metrics/api/#asynchronous-counter)
|
|
2474
|
+
about asynchronous counter.
|
|
2475
|
+
|
|
2476
|
+
Args:
|
|
2477
|
+
name: The name of the metric.
|
|
2478
|
+
callbacks: A sequence of callbacks that return an iterable of
|
|
2479
|
+
[Observation](https://opentelemetry-python.readthedocs.io/en/latest/api/metrics.html#opentelemetry.metrics.Observation).
|
|
2480
|
+
unit: The unit of the metric.
|
|
2481
|
+
description: The description of the metric.
|
|
2482
|
+
"""
|
|
2483
|
+
self._meter.create_observable_counter(name, callbacks, unit, description)
|
|
2484
|
+
|
|
2485
|
+
def metric_gauge_callback(
|
|
2486
|
+
self, name: str, callbacks: Sequence[CallbackT], *, unit: str = '', description: str = ''
|
|
2487
|
+
) -> None:
|
|
2488
|
+
"""Create a gauge metric that uses a callback to collect observations.
|
|
2489
|
+
|
|
2490
|
+
The callback is called every 60 seconds in a background thread.
|
|
2491
|
+
|
|
2492
|
+
The gauge metric is a metric that represents a single numerical value that can arbitrarily go up and down.
|
|
2493
|
+
|
|
2494
|
+
```py
|
|
2495
|
+
import threading
|
|
2496
|
+
|
|
2497
|
+
from opentelemetry.metrics import CallbackOptions, Observation
|
|
2498
|
+
|
|
2499
|
+
import logfire
|
|
2500
|
+
|
|
2501
|
+
logfire.configure()
|
|
2502
|
+
|
|
2503
|
+
|
|
2504
|
+
def thread_count_callback(options: CallbackOptions):
|
|
2505
|
+
yield Observation(threading.active_count())
|
|
2506
|
+
|
|
2507
|
+
|
|
2508
|
+
logfire.metric_gauge_callback(
|
|
2509
|
+
'system.thread_count',
|
|
2510
|
+
callbacks=[thread_count_callback],
|
|
2511
|
+
unit='1',
|
|
2512
|
+
description='Number of threads',
|
|
2513
|
+
)
|
|
2514
|
+
```
|
|
2515
|
+
|
|
2516
|
+
See the [Opentelemetry documentation](https://opentelemetry.io/docs/specs/otel/metrics/api/#asynchronous-gauge)
|
|
2517
|
+
about asynchronous gauge.
|
|
2518
|
+
|
|
2519
|
+
Args:
|
|
2520
|
+
name: The name of the metric.
|
|
2521
|
+
callbacks: A sequence of callbacks that return an iterable of
|
|
2522
|
+
[Observation](https://opentelemetry-python.readthedocs.io/en/latest/api/metrics.html#opentelemetry.metrics.Observation).
|
|
2523
|
+
unit: The unit of the metric.
|
|
2524
|
+
description: The description of the metric.
|
|
2525
|
+
"""
|
|
2526
|
+
self._meter.create_observable_gauge(name, callbacks, unit, description)
|
|
2527
|
+
|
|
2528
|
+
def metric_up_down_counter_callback(
|
|
2529
|
+
self, name: str, callbacks: Sequence[CallbackT], *, unit: str = '', description: str = ''
|
|
2530
|
+
) -> None:
|
|
2531
|
+
"""Create an up-down counter metric that uses a callback to collect observations.
|
|
2532
|
+
|
|
2533
|
+
The callback is called every 60 seconds in a background thread.
|
|
2534
|
+
|
|
2535
|
+
The up-down counter is a cumulative metric that represents a single numerical value that can be adjusted up or
|
|
2536
|
+
down.
|
|
2537
|
+
|
|
2538
|
+
```py
|
|
2539
|
+
from opentelemetry.metrics import CallbackOptions, Observation
|
|
2540
|
+
|
|
2541
|
+
import logfire
|
|
2542
|
+
|
|
2543
|
+
logfire.configure()
|
|
2544
|
+
|
|
2545
|
+
items = []
|
|
2546
|
+
|
|
2547
|
+
|
|
2548
|
+
def inventory_callback(options: CallbackOptions):
|
|
2549
|
+
yield Observation(len(items))
|
|
2550
|
+
|
|
2551
|
+
|
|
2552
|
+
logfire.metric_up_down_counter_callback(
|
|
2553
|
+
name='store.inventory',
|
|
2554
|
+
description='Number of items in the inventory',
|
|
2555
|
+
callbacks=[inventory_callback],
|
|
2556
|
+
)
|
|
2557
|
+
```
|
|
2558
|
+
|
|
2559
|
+
See the [Opentelemetry documentation](https://opentelemetry.io/docs/specs/otel/metrics/api/#asynchronous-updowncounter)
|
|
2560
|
+
about asynchronous up-down counters.
|
|
2561
|
+
|
|
2562
|
+
Args:
|
|
2563
|
+
name: The name of the metric.
|
|
2564
|
+
callbacks: A sequence of callbacks that return an iterable of
|
|
2565
|
+
[Observation](https://opentelemetry-python.readthedocs.io/en/latest/api/metrics.html#opentelemetry.metrics.Observation).
|
|
2566
|
+
unit: The unit of the metric.
|
|
2567
|
+
description: The description of the metric.
|
|
2568
|
+
"""
|
|
2569
|
+
self._meter.create_observable_up_down_counter(name, callbacks, unit, description)
|
|
2570
|
+
|
|
2571
|
+
def suppress_scopes(self, *scopes: str) -> None:
|
|
2572
|
+
"""Prevent spans and metrics from being created for the given OpenTelemetry scope names.
|
|
2573
|
+
|
|
2574
|
+
To get the scope name of a span/metric,
|
|
2575
|
+
check the value of the `otel_scope_name` column in the Logfire database.
|
|
2576
|
+
"""
|
|
2577
|
+
self._config.suppress_scopes(*scopes)
|
|
2578
|
+
|
|
2579
|
+
def shutdown(self, timeout_millis: int = 30_000, flush: bool = True) -> bool: # pragma: no cover
|
|
2580
|
+
"""Shut down all tracers and meters.
|
|
2581
|
+
|
|
2582
|
+
This will clean up any resources used by the tracers and meters and flush any remaining spans and metrics.
|
|
2583
|
+
|
|
2584
|
+
Args:
|
|
2585
|
+
timeout_millis: The timeout in milliseconds.
|
|
2586
|
+
flush: Whether to flush remaining spans and metrics before shutting down.
|
|
2587
|
+
|
|
2588
|
+
Returns:
|
|
2589
|
+
`False` if the timeout was reached before the shutdown was completed, `True` otherwise.
|
|
2590
|
+
"""
|
|
2591
|
+
return self._config.shutdown(timeout_millis=timeout_millis, flush=flush)
|
|
2592
|
+
|
|
2593
|
+
@overload
|
|
2594
|
+
def var(
|
|
2595
|
+
self,
|
|
2596
|
+
name: str,
|
|
2597
|
+
*,
|
|
2598
|
+
default: T,
|
|
2599
|
+
description: str | None = None,
|
|
2600
|
+
) -> Variable[T]: ...
|
|
2601
|
+
|
|
2602
|
+
@overload
|
|
2603
|
+
def var(
|
|
2604
|
+
self,
|
|
2605
|
+
name: str,
|
|
2606
|
+
*,
|
|
2607
|
+
type: type[T],
|
|
2608
|
+
default: T | ResolveFunction[T],
|
|
2609
|
+
description: str | None = None,
|
|
2610
|
+
) -> Variable[T]: ...
|
|
2611
|
+
|
|
2612
|
+
def var(
|
|
2613
|
+
self,
|
|
2614
|
+
name: str,
|
|
2615
|
+
*,
|
|
2616
|
+
type: type[T] | None = None,
|
|
2617
|
+
default: T | ResolveFunction[T],
|
|
2618
|
+
description: str | None = None,
|
|
2619
|
+
) -> Variable[T]:
|
|
2620
|
+
"""Define a managed variable.
|
|
2621
|
+
|
|
2622
|
+
Managed variables let you externalize runtime configuration from your code,
|
|
2623
|
+
controlling values from the Logfire UI without redeploying. Use `.get()` on the
|
|
2624
|
+
returned `Variable` to resolve the current value.
|
|
2625
|
+
|
|
2626
|
+
See the [managed variables guide](https://logfire.pydantic.dev/docs/reference/advanced/managed-variables/)
|
|
2627
|
+
for more details.
|
|
2628
|
+
|
|
2629
|
+
```py
|
|
2630
|
+
import logfire
|
|
2631
|
+
|
|
2632
|
+
logfire.configure()
|
|
2633
|
+
|
|
2634
|
+
# Simple primitive variable (type inferred from default)
|
|
2635
|
+
feature_enabled = logfire.var('feature_enabled', default=False)
|
|
2636
|
+
|
|
2637
|
+
# Use the variable
|
|
2638
|
+
with feature_enabled.get(targeting_key='user-123') as resolved:
|
|
2639
|
+
if resolved.value:
|
|
2640
|
+
...
|
|
2641
|
+
```
|
|
2642
|
+
|
|
2643
|
+
For variables whose values contain Handlebars `{{placeholder}}` templates that
|
|
2644
|
+
need runtime inputs, we recommend [`template_var()`][logfire.Logfire.template_var]:
|
|
2645
|
+
it renders the templates as part of resolution and gives you a typed
|
|
2646
|
+
`get(inputs)` API. Under the hood it uses `pydantic_handlebars.render`, which
|
|
2647
|
+
you can also call yourself on the resolved value if you need to drive rendering
|
|
2648
|
+
manually.
|
|
2649
|
+
|
|
2650
|
+
Args:
|
|
2651
|
+
name: Unique identifier for the variable. Must match the name configured in the
|
|
2652
|
+
Logfire UI when using remote variables.
|
|
2653
|
+
type: Expected type for validation and JSON schema generation. Can be a primitive
|
|
2654
|
+
type or a Pydantic model. If not provided, the type is inferred from `default`.
|
|
2655
|
+
Required when `default` is a resolve function.
|
|
2656
|
+
default: Default value used when no remote configuration is found.
|
|
2657
|
+
When `type` is not provided, the type is inferred from this value.
|
|
2658
|
+
Can also be a callable with `targeting_key` and `attributes` parameters
|
|
2659
|
+
(requires `type` to be set explicitly).
|
|
2660
|
+
description: Optional human-readable description of what the variable controls.
|
|
2661
|
+
"""
|
|
2662
|
+
from logfire.variables import ensure_variables_dependencies
|
|
2663
|
+
|
|
2664
|
+
ensure_variables_dependencies()
|
|
2665
|
+
|
|
2666
|
+
from logfire.variables.variable import Variable, is_resolve_function
|
|
2667
|
+
|
|
2668
|
+
if type is None:
|
|
2669
|
+
if is_resolve_function(default):
|
|
2670
|
+
raise TypeError(
|
|
2671
|
+
'When `default` is a resolve function (callable with targeting_key and attributes parameters), '
|
|
2672
|
+
'`type` must be provided to specify the variable value type.'
|
|
2673
|
+
)
|
|
2674
|
+
if default is None:
|
|
2675
|
+
raise TypeError(
|
|
2676
|
+
'When `default` is None, `type` must be provided (e.g. `type=Optional[int]`); '
|
|
2677
|
+
'the variable value type cannot be inferred from a None default.'
|
|
2678
|
+
)
|
|
2679
|
+
tp = cast(Type[T], default.__class__) # noqa UP006
|
|
2680
|
+
else:
|
|
2681
|
+
tp = type
|
|
2682
|
+
|
|
2683
|
+
import re
|
|
2684
|
+
|
|
2685
|
+
if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]*$', name):
|
|
2686
|
+
raise ValueError(
|
|
2687
|
+
f"Invalid variable name '{name}'. "
|
|
2688
|
+
'Variable names must be valid Python identifiers (letters, digits, and underscores, '
|
|
2689
|
+
'not starting with a digit).'
|
|
2690
|
+
)
|
|
2691
|
+
|
|
2692
|
+
# Variables are expected to be defined once at import time (single-threaded), so this
|
|
2693
|
+
# check-then-insert is not locked. If you register variables concurrently from multiple
|
|
2694
|
+
# threads, guard your own registration to preserve the uniqueness guarantee.
|
|
2695
|
+
if name in self._variables:
|
|
2696
|
+
raise ValueError(
|
|
2697
|
+
f"A variable with name '{name}' has already been registered. Each variable must have a unique name."
|
|
2698
|
+
)
|
|
2699
|
+
|
|
2700
|
+
variable = Variable[T](
|
|
2701
|
+
name,
|
|
2702
|
+
default=default,
|
|
2703
|
+
type=tp,
|
|
2704
|
+
logfire_instance=self,
|
|
2705
|
+
description=description,
|
|
2706
|
+
)
|
|
2707
|
+
self._variables[name] = variable
|
|
2708
|
+
|
|
2709
|
+
from logfire.variables.variable import warn_on_template_inputs_composition_mismatch
|
|
2710
|
+
|
|
2711
|
+
warn_on_template_inputs_composition_mismatch(self._variables, variable)
|
|
2712
|
+
|
|
2713
|
+
return variable
|
|
2714
|
+
|
|
2715
|
+
@overload
|
|
2716
|
+
def template_var(
|
|
2717
|
+
self,
|
|
2718
|
+
name: str,
|
|
2719
|
+
*,
|
|
2720
|
+
default: T,
|
|
2721
|
+
inputs_type: type[InputsT],
|
|
2722
|
+
description: str | None = None,
|
|
2723
|
+
template_mismatch_policy: TemplateMismatchPolicy | None = None,
|
|
2724
|
+
) -> TemplateVariable[T, InputsT]: ...
|
|
2725
|
+
|
|
2726
|
+
@overload
|
|
2727
|
+
def template_var(
|
|
2728
|
+
self,
|
|
2729
|
+
name: str,
|
|
2730
|
+
*,
|
|
2731
|
+
type: type[T],
|
|
2732
|
+
default: T | ResolveFunction[T],
|
|
2733
|
+
inputs_type: type[InputsT],
|
|
2734
|
+
description: str | None = None,
|
|
2735
|
+
template_mismatch_policy: TemplateMismatchPolicy | None = None,
|
|
2736
|
+
) -> TemplateVariable[T, InputsT]: ...
|
|
2737
|
+
|
|
2738
|
+
def template_var(
|
|
2739
|
+
self,
|
|
2740
|
+
name: str,
|
|
2741
|
+
*,
|
|
2742
|
+
type: type[T] | None = None,
|
|
2743
|
+
default: T | ResolveFunction[T],
|
|
2744
|
+
inputs_type: type[InputsT],
|
|
2745
|
+
description: str | None = None,
|
|
2746
|
+
template_mismatch_policy: TemplateMismatchPolicy | None = None,
|
|
2747
|
+
) -> TemplateVariable[T, InputsT]:
|
|
2748
|
+
"""Define a managed template variable with integrated rendering.
|
|
2749
|
+
|
|
2750
|
+
Like `var()`, but `get(inputs)` automatically renders Handlebars `{{placeholder}}`
|
|
2751
|
+
templates in the resolved value before returning. The pipeline is:
|
|
2752
|
+
resolve → compose `@{refs}@` → render `{{}}` → deserialize.
|
|
2753
|
+
|
|
2754
|
+
```py skip-run="true" skip-reason="requires-pydantic-handlebars"
|
|
2755
|
+
from pydantic import BaseModel
|
|
2756
|
+
|
|
2757
|
+
import logfire
|
|
2758
|
+
|
|
2759
|
+
logfire.configure()
|
|
2760
|
+
|
|
2761
|
+
|
|
2762
|
+
class PromptInputs(BaseModel):
|
|
2763
|
+
user_name: str
|
|
2764
|
+
is_premium: bool = False
|
|
2765
|
+
|
|
2766
|
+
|
|
2767
|
+
prompt = logfire.template_var(
|
|
2768
|
+
'system_prompt',
|
|
2769
|
+
default='Hello {{user_name}}',
|
|
2770
|
+
inputs_type=PromptInputs,
|
|
2771
|
+
)
|
|
2772
|
+
|
|
2773
|
+
with prompt.get(PromptInputs(user_name='Alice')) as resolved:
|
|
2774
|
+
assert resolved.value == 'Hello Alice'
|
|
2775
|
+
```
|
|
2776
|
+
|
|
2777
|
+
Args:
|
|
2778
|
+
name: Unique identifier for the variable.
|
|
2779
|
+
type: Expected type for validation and JSON schema generation. Can be a primitive
|
|
2780
|
+
type or a Pydantic model. If not provided, the type is inferred from `default`.
|
|
2781
|
+
Required when `default` is a resolve function.
|
|
2782
|
+
default: Default value used when no remote configuration is found.
|
|
2783
|
+
When `type` is not provided, the type is inferred from this value.
|
|
2784
|
+
Can also be a callable with `targeting_key` and `attributes` parameters
|
|
2785
|
+
(requires `type` to be set explicitly).
|
|
2786
|
+
inputs_type: The type (typically a Pydantic `BaseModel`) describing the expected
|
|
2787
|
+
template inputs. Used for type-safe `get(inputs)` calls and JSON schema generation.
|
|
2788
|
+
description: Optional human-readable description of what the variable controls.
|
|
2789
|
+
template_mismatch_policy: How to react when the resolved (post-composition) template
|
|
2790
|
+
references a `{{field}}` not declared in `inputs_type`. `'warn'` emits a
|
|
2791
|
+
`RuntimeWarning` and renders the undeclared field as the empty string;
|
|
2792
|
+
`'error'` raises `TemplateInputsMismatchError`; `'ignore'` renders silently.
|
|
2793
|
+
Defaults to inheriting from `VariablesOptions` / `LocalVariablesOptions`
|
|
2794
|
+
(which default to `'warn'`). Pass an explicit value to override the
|
|
2795
|
+
instance-level policy for this variable only — even to relax it.
|
|
2796
|
+
"""
|
|
2797
|
+
import re
|
|
2798
|
+
|
|
2799
|
+
from logfire.variables import ensure_variables_dependencies
|
|
2800
|
+
|
|
2801
|
+
ensure_variables_dependencies()
|
|
2802
|
+
|
|
2803
|
+
from logfire.variables.variable import TemplateVariable, is_resolve_function
|
|
2804
|
+
|
|
2805
|
+
if type is None:
|
|
2806
|
+
if is_resolve_function(default):
|
|
2807
|
+
raise TypeError(
|
|
2808
|
+
'When `default` is a resolve function (callable with targeting_key and attributes parameters), '
|
|
2809
|
+
'`type` must be provided to specify the variable value type.'
|
|
2810
|
+
)
|
|
2811
|
+
if default is None:
|
|
2812
|
+
raise TypeError(
|
|
2813
|
+
'When `default` is None, `type` must be provided (e.g. `type=Optional[int]`); '
|
|
2814
|
+
'the variable value type cannot be inferred from a None default.'
|
|
2815
|
+
)
|
|
2816
|
+
tp = cast(Type[T], default.__class__) # noqa UP006
|
|
2817
|
+
else:
|
|
2818
|
+
tp = type
|
|
2819
|
+
|
|
2820
|
+
if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]*$', name):
|
|
2821
|
+
raise ValueError(
|
|
2822
|
+
f"Invalid variable name '{name}'. "
|
|
2823
|
+
'Variable names must be valid Python identifiers (letters, digits, and underscores, '
|
|
2824
|
+
'not starting with a digit).'
|
|
2825
|
+
)
|
|
2826
|
+
|
|
2827
|
+
# Variables are expected to be defined once at import time (single-threaded), so this
|
|
2828
|
+
# check-then-insert is not locked. If you register variables concurrently from multiple
|
|
2829
|
+
# threads, guard your own registration to preserve the uniqueness guarantee.
|
|
2830
|
+
if name in self._variables:
|
|
2831
|
+
raise ValueError(
|
|
2832
|
+
f"A variable with name '{name}' has already been registered. Each variable must have a unique name."
|
|
2833
|
+
)
|
|
2834
|
+
|
|
2835
|
+
variable = TemplateVariable[T, InputsT](
|
|
2836
|
+
name,
|
|
2837
|
+
type=tp,
|
|
2838
|
+
default=default,
|
|
2839
|
+
inputs_type=inputs_type,
|
|
2840
|
+
description=description,
|
|
2841
|
+
logfire_instance=self,
|
|
2842
|
+
template_mismatch_policy=template_mismatch_policy,
|
|
2843
|
+
)
|
|
2844
|
+
self._variables[name] = variable
|
|
2845
|
+
|
|
2846
|
+
from logfire.variables.variable import warn_on_template_inputs_composition_mismatch
|
|
2847
|
+
|
|
2848
|
+
warn_on_template_inputs_composition_mismatch(self._variables, variable)
|
|
2849
|
+
|
|
2850
|
+
return variable
|
|
2851
|
+
|
|
2852
|
+
def variables_clear(self) -> None:
|
|
2853
|
+
"""Clear all variables registered with this Logfire instance's config.
|
|
2854
|
+
|
|
2855
|
+
This removes all variables previously registered via [`var()`][logfire.Logfire.var]
|
|
2856
|
+
or [`template_var()`][logfire.Logfire.template_var] on this instance or any
|
|
2857
|
+
[`with_settings()`][logfire.Logfire.with_settings] sibling that shares its config,
|
|
2858
|
+
allowing them to be re-registered. This is primarily intended for use in tests to
|
|
2859
|
+
ensure a clean state between test cases.
|
|
2860
|
+
"""
|
|
2861
|
+
self._variables.clear()
|
|
2862
|
+
|
|
2863
|
+
def variables_get(self) -> list[Variable[Any] | TemplateVariable[Any, Any]]:
|
|
2864
|
+
"""Get all variables registered with this Logfire instance's config."""
|
|
2865
|
+
return list(self._variables.values())
|
|
2866
|
+
|
|
2867
|
+
def variables_push(
|
|
2868
|
+
self,
|
|
2869
|
+
variables: list[Variable[Any] | TemplateVariable[Any, Any]] | None = None,
|
|
2870
|
+
*,
|
|
2871
|
+
dry_run: bool = False,
|
|
2872
|
+
yes: bool = False,
|
|
2873
|
+
strict: bool = True,
|
|
2874
|
+
) -> bool:
|
|
2875
|
+
"""Push variable definitions (metadata only) to the configured variable provider.
|
|
2876
|
+
|
|
2877
|
+
This method syncs local variable definitions with the provider:
|
|
2878
|
+
- Creates new variables that don't exist in the provider
|
|
2879
|
+
- Updates JSON schemas for existing variables if they've changed
|
|
2880
|
+
- Warns about existing label values that are incompatible with new schemas
|
|
2881
|
+
|
|
2882
|
+
The provider is determined by the Logfire configuration. For remote providers,
|
|
2883
|
+
this requires proper authentication (via VariablesOptions or LOGFIRE_API_KEY).
|
|
2884
|
+
|
|
2885
|
+
Args:
|
|
2886
|
+
variables: Variable instances to push. If None, all variables
|
|
2887
|
+
registered with this Logfire instance's config will be pushed, including
|
|
2888
|
+
variables registered on `with_settings()` siblings.
|
|
2889
|
+
dry_run: If True, only show what would change without applying.
|
|
2890
|
+
yes: If True, skip confirmation prompt.
|
|
2891
|
+
strict: If True, fail on incompatible label values, missing references, or template-field issues.
|
|
2892
|
+
Set to False to publish despite those issues. Reference cycles always block the push.
|
|
2893
|
+
|
|
2894
|
+
Returns:
|
|
2895
|
+
True if changes were applied (or would be applied in dry_run mode), False otherwise.
|
|
2896
|
+
|
|
2897
|
+
Example:
|
|
2898
|
+
```python
|
|
2899
|
+
import logfire
|
|
2900
|
+
|
|
2901
|
+
feature_enabled = logfire.var(name='feature_enabled', type=bool, default=False)
|
|
2902
|
+
max_retries = logfire.var(name='max_retries', type=int, default=3)
|
|
2903
|
+
|
|
2904
|
+
if __name__ == '__main__':
|
|
2905
|
+
# Push all registered variables
|
|
2906
|
+
logfire.variables_push()
|
|
2907
|
+
|
|
2908
|
+
# Or push specific variables only
|
|
2909
|
+
logfire.variables_push([feature_enabled])
|
|
2910
|
+
```
|
|
2911
|
+
"""
|
|
2912
|
+
if variables is None:
|
|
2913
|
+
variables = self.variables_get() # pragma: no cover
|
|
2914
|
+
|
|
2915
|
+
provider = self.config.get_variable_provider()
|
|
2916
|
+
return provider.push_variables(variables, dry_run=dry_run, yes=yes, strict=strict)
|
|
2917
|
+
|
|
2918
|
+
def variables_push_types(
|
|
2919
|
+
self,
|
|
2920
|
+
types: Sequence[type[Any] | tuple[type[Any], str]],
|
|
2921
|
+
*,
|
|
2922
|
+
dry_run: bool = False,
|
|
2923
|
+
yes: bool = False,
|
|
2924
|
+
strict: bool = True,
|
|
2925
|
+
) -> bool:
|
|
2926
|
+
"""Push variable type definitions to the configured variable provider.
|
|
2927
|
+
|
|
2928
|
+
Variable types are reusable schema definitions that can be referenced by variables.
|
|
2929
|
+
They help organize and standardize variable schemas across your project.
|
|
2930
|
+
|
|
2931
|
+
This method syncs local Python types with the provider:
|
|
2932
|
+
- Creates new types that don't exist in the provider
|
|
2933
|
+
- Updates schemas for existing types if they've changed
|
|
2934
|
+
- Shows a diff of changes before applying
|
|
2935
|
+
- Checks if existing variable label values are compatible with the new schemas
|
|
2936
|
+
|
|
2937
|
+
The provider is determined by the Logfire configuration. For remote providers,
|
|
2938
|
+
this requires proper authentication (via VariablesOptions or LOGFIRE_API_KEY).
|
|
2939
|
+
|
|
2940
|
+
Args:
|
|
2941
|
+
types: Types to push. Items can be:
|
|
2942
|
+
- A type (name defaults to __name__ or str(type))
|
|
2943
|
+
- A tuple of (type, name) for explicit naming
|
|
2944
|
+
dry_run: If True, only show what would change without applying.
|
|
2945
|
+
yes: If True, skip confirmation prompt.
|
|
2946
|
+
strict: If True, abort when existing label values are incompatible with
|
|
2947
|
+
the new type schema. Set to False to publish despite these issues.
|
|
2948
|
+
|
|
2949
|
+
Returns:
|
|
2950
|
+
True if changes were applied (or would be applied in dry_run mode), False otherwise.
|
|
2951
|
+
|
|
2952
|
+
Example:
|
|
2953
|
+
```python
|
|
2954
|
+
import logfire
|
|
2955
|
+
from pydantic import BaseModel
|
|
2956
|
+
|
|
2957
|
+
|
|
2958
|
+
class FeatureConfig(BaseModel):
|
|
2959
|
+
enabled: bool = False
|
|
2960
|
+
max_retries: int = 3
|
|
2961
|
+
timeout_seconds: float = 30.0
|
|
2962
|
+
|
|
2963
|
+
|
|
2964
|
+
class UserSettings(BaseModel):
|
|
2965
|
+
theme: str = 'light'
|
|
2966
|
+
notifications_enabled: bool = True
|
|
2967
|
+
|
|
2968
|
+
|
|
2969
|
+
if __name__ == '__main__':
|
|
2970
|
+
# Push type definitions using their class names
|
|
2971
|
+
logfire.variables_push_types([FeatureConfig, UserSettings])
|
|
2972
|
+
|
|
2973
|
+
# Or push with explicit names
|
|
2974
|
+
logfire.variables_push_types(
|
|
2975
|
+
[
|
|
2976
|
+
(FeatureConfig, 'my-feature-config'),
|
|
2977
|
+
(UserSettings, 'my-user-settings'),
|
|
2978
|
+
]
|
|
2979
|
+
)
|
|
2980
|
+
```
|
|
2981
|
+
"""
|
|
2982
|
+
provider = self.config.get_variable_provider()
|
|
2983
|
+
return provider.push_variable_types(types, dry_run=dry_run, yes=yes, strict=strict)
|
|
2984
|
+
|
|
2985
|
+
def variables_validate(
|
|
2986
|
+
self,
|
|
2987
|
+
variables: list[Variable[Any] | TemplateVariable[Any, Any]] | None = None,
|
|
2988
|
+
) -> ValidationReport:
|
|
2989
|
+
"""Validate that provider-side variable label values match local type definitions.
|
|
2990
|
+
|
|
2991
|
+
This method fetches the current variable configuration from the provider and
|
|
2992
|
+
validates that all label values can be deserialized to the expected types
|
|
2993
|
+
defined in the local Variable instances.
|
|
2994
|
+
|
|
2995
|
+
Args:
|
|
2996
|
+
variables: Variable instances to validate. If None, all variables
|
|
2997
|
+
registered with this Logfire instance's config will be validated, including
|
|
2998
|
+
variables registered on `with_settings()` siblings.
|
|
2999
|
+
|
|
3000
|
+
Returns:
|
|
3001
|
+
A ValidationReport containing any errors found. Use `report.is_valid` to check
|
|
3002
|
+
if validation passed, and `report.format()` to get a human-readable summary.
|
|
3003
|
+
|
|
3004
|
+
Example:
|
|
3005
|
+
```python
|
|
3006
|
+
import logfire
|
|
3007
|
+
|
|
3008
|
+
feature_enabled = logfire.var(name='feature_enabled', type=bool, default=False)
|
|
3009
|
+
max_retries = logfire.var(name='max_retries', type=int, default=3)
|
|
3010
|
+
|
|
3011
|
+
if __name__ == '__main__':
|
|
3012
|
+
# Validate all registered variables
|
|
3013
|
+
logfire.variables_validate()
|
|
3014
|
+
|
|
3015
|
+
# Or validate specific variables only
|
|
3016
|
+
report = logfire.variables_validate([feature_enabled])
|
|
3017
|
+
assert report.is_valid
|
|
3018
|
+
```
|
|
3019
|
+
"""
|
|
3020
|
+
if variables is None:
|
|
3021
|
+
variables = self.variables_get() # pragma: no cover
|
|
3022
|
+
|
|
3023
|
+
provider = self.config.get_variable_provider()
|
|
3024
|
+
return provider.validate_variables(variables)
|
|
3025
|
+
|
|
3026
|
+
def variables_push_config(
|
|
3027
|
+
self,
|
|
3028
|
+
config: VariablesConfig,
|
|
3029
|
+
*,
|
|
3030
|
+
mode: Literal['merge', 'replace'] = 'merge',
|
|
3031
|
+
dry_run: bool = False,
|
|
3032
|
+
yes: bool = False,
|
|
3033
|
+
) -> bool: # pragma: no cover
|
|
3034
|
+
"""Push a VariablesConfig to the configured provider.
|
|
3035
|
+
|
|
3036
|
+
This method pushes a VariablesConfig (including labels and rollouts) to the
|
|
3037
|
+
provider. For remote providers, version records are created from label
|
|
3038
|
+
entries with inline serialized values; `latest_version` is pull/read state
|
|
3039
|
+
derived by the server and is not pushed directly. It's useful for:
|
|
3040
|
+
- Pushing configs generated or modified locally
|
|
3041
|
+
- Pushing configs read from files
|
|
3042
|
+
- Partial updates (merge mode) or full replacement (replace mode)
|
|
3043
|
+
|
|
3044
|
+
Args:
|
|
3045
|
+
config: The VariablesConfig to sync.
|
|
3046
|
+
mode: 'merge' updates/creates only variables in config (leaves others unchanged).
|
|
3047
|
+
'replace' makes the server match the config exactly (deletes missing variables).
|
|
3048
|
+
dry_run: If True, only show what would change without applying.
|
|
3049
|
+
yes: If True, skip confirmation prompt.
|
|
3050
|
+
|
|
3051
|
+
Returns:
|
|
3052
|
+
True if changes were applied (or would be applied in dry_run mode), False otherwise.
|
|
3053
|
+
|
|
3054
|
+
Example:
|
|
3055
|
+
```python skip="true"
|
|
3056
|
+
import logfire
|
|
3057
|
+
from logfire.variables import VariablesConfig
|
|
3058
|
+
|
|
3059
|
+
# Push config to server
|
|
3060
|
+
logfire.variables_push_config(config)
|
|
3061
|
+
|
|
3062
|
+
# Or merge just a subset of variables
|
|
3063
|
+
logfire.variables_push_config(config, mode='merge')
|
|
3064
|
+
```
|
|
3065
|
+
"""
|
|
3066
|
+
provider = self.config.get_variable_provider()
|
|
3067
|
+
return provider.push_config(config, mode=mode, dry_run=dry_run, yes=yes)
|
|
3068
|
+
|
|
3069
|
+
def variables_pull_config(self) -> VariablesConfig: # pragma: no cover
|
|
3070
|
+
"""Pull the current variable configuration from the provider.
|
|
3071
|
+
|
|
3072
|
+
This method fetches the complete configuration from the provider,
|
|
3073
|
+
useful for generating local copies of the config that can be modified.
|
|
3074
|
+
|
|
3075
|
+
Returns:
|
|
3076
|
+
The current VariablesConfig from the provider.
|
|
3077
|
+
|
|
3078
|
+
Example:
|
|
3079
|
+
```python skip="true"
|
|
3080
|
+
import logfire
|
|
3081
|
+
|
|
3082
|
+
# Pull config from the provider
|
|
3083
|
+
config = logfire.variables_pull_config()
|
|
3084
|
+
print(config.model_dump_json(indent=2))
|
|
3085
|
+
```
|
|
3086
|
+
"""
|
|
3087
|
+
provider = self.config.get_variable_provider()
|
|
3088
|
+
return provider.pull_config()
|
|
3089
|
+
|
|
3090
|
+
def variables_build_config(
|
|
3091
|
+
self,
|
|
3092
|
+
variables: list[Variable[Any] | TemplateVariable[Any, Any]] | None = None,
|
|
3093
|
+
) -> VariablesConfig:
|
|
3094
|
+
"""Build a VariablesConfig from registered Variable instances.
|
|
3095
|
+
|
|
3096
|
+
This creates a minimal config with just the name, schema, and example for each variable.
|
|
3097
|
+
No labels or versions are created - use this to build a template config that can be edited.
|
|
3098
|
+
|
|
3099
|
+
Args:
|
|
3100
|
+
variables: Variable instances to include. If None, uses all variables registered
|
|
3101
|
+
with this Logfire instance's config, including variables registered on
|
|
3102
|
+
`with_settings()` siblings.
|
|
3103
|
+
|
|
3104
|
+
Returns:
|
|
3105
|
+
A VariablesConfig with minimal configs for each variable.
|
|
3106
|
+
|
|
3107
|
+
Example:
|
|
3108
|
+
```python skip="true"
|
|
3109
|
+
import logfire
|
|
3110
|
+
|
|
3111
|
+
feature_enabled = logfire.var(name='feature_enabled', type=bool, default=False)
|
|
3112
|
+
max_retries = logfire.var(name='max_retries', type=int, default=3)
|
|
3113
|
+
|
|
3114
|
+
# Build config from registered variables
|
|
3115
|
+
config = logfire.variables_build_config()
|
|
3116
|
+
print(config.model_dump_json(indent=2))
|
|
3117
|
+
```
|
|
3118
|
+
"""
|
|
3119
|
+
if variables is None:
|
|
3120
|
+
variables = self.variables_get() # pragma: no cover
|
|
3121
|
+
|
|
3122
|
+
from logfire.variables.config import VariablesConfig
|
|
3123
|
+
|
|
3124
|
+
return VariablesConfig.from_variables(variables)
|
|
3125
|
+
|
|
3126
|
+
def forward_export_request(
|
|
3127
|
+
self,
|
|
3128
|
+
*,
|
|
3129
|
+
path: str,
|
|
3130
|
+
headers: Mapping[str, str],
|
|
3131
|
+
body: bytes,
|
|
3132
|
+
max_body_size: int = 50 * 1024 * 1024,
|
|
3133
|
+
) -> ForwardExportRequestResponse:
|
|
3134
|
+
"""Forward an OpenTelemetry export request to the Logfire backend.
|
|
3135
|
+
|
|
3136
|
+
This method is generic and can be used for any web framework.
|
|
3137
|
+
For Starlette/FastAPI, use `forward_export_request_starlette` instead for extra protection and convenience.
|
|
3138
|
+
|
|
3139
|
+
This is for proxying telemetry from a browser to Logfire so that the write token doesn't need to be
|
|
3140
|
+
exposed in the frontend code.
|
|
3141
|
+
See https://pydantic.dev/docs/logfire/instrument/typescript/packages/browser/#python-backend-proxy
|
|
3142
|
+
for more details.
|
|
3143
|
+
|
|
3144
|
+
We recommend protecting the endpoint that uses this method with authentication, rate limiting, and CORS.
|
|
3145
|
+
|
|
3146
|
+
Args:
|
|
3147
|
+
path: one of "/v1/traces", "/v1/metrics", or "/v1/logs"
|
|
3148
|
+
headers: the request headers, as a mapping of header names to values
|
|
3149
|
+
body: the request body, as bytes
|
|
3150
|
+
max_body_size: the maximum allowed body size, in bytes.
|
|
3151
|
+
If the body exceeds this size, the response will be a 413, rejecting the payload.
|
|
3152
|
+
|
|
3153
|
+
Returns:
|
|
3154
|
+
A `ForwardExportRequestResponse` containing the response status code, body, and headers.
|
|
3155
|
+
"""
|
|
3156
|
+
from .forwarding import forward_export_request
|
|
3157
|
+
|
|
3158
|
+
return forward_export_request(
|
|
3159
|
+
path=path,
|
|
3160
|
+
headers=headers,
|
|
3161
|
+
body=body,
|
|
3162
|
+
max_body_size=max_body_size,
|
|
3163
|
+
logfire_instance=self,
|
|
3164
|
+
)
|
|
3165
|
+
|
|
3166
|
+
async def forward_export_request_starlette(
|
|
3167
|
+
self,
|
|
3168
|
+
request: Request,
|
|
3169
|
+
*,
|
|
3170
|
+
max_body_size: int = 50 * 1024 * 1024,
|
|
3171
|
+
) -> Response:
|
|
3172
|
+
"""Forward an OpenTelemetry export request to the Logfire backend.
|
|
3173
|
+
|
|
3174
|
+
This method is designed for Starlette/FastAPI.
|
|
3175
|
+
For other web frameworks, use `forward_export_request` instead and adapt the request/response handling as needed.
|
|
3176
|
+
|
|
3177
|
+
This is for proxying telemetry from a browser to Logfire so that the write token doesn't need to be
|
|
3178
|
+
exposed in the frontend code.
|
|
3179
|
+
See https://pydantic.dev/docs/logfire/instrument/typescript/packages/browser/#python-backend-proxy
|
|
3180
|
+
for more details.
|
|
3181
|
+
|
|
3182
|
+
We recommend protecting the endpoint that uses this method with authentication, rate limiting, and CORS.
|
|
3183
|
+
|
|
3184
|
+
Args:
|
|
3185
|
+
request: The Starlette/FastAPI `Request` object.
|
|
3186
|
+
max_body_size: the maximum allowed body size, in bytes.
|
|
3187
|
+
If the body exceeds this size, the response will be a 413, rejecting the payload.
|
|
3188
|
+
|
|
3189
|
+
Returns:
|
|
3190
|
+
A Starlette/FastAPI `Response` object.
|
|
3191
|
+
"""
|
|
3192
|
+
from .forwarding import logfire_proxy
|
|
3193
|
+
|
|
3194
|
+
return await logfire_proxy(
|
|
3195
|
+
request=request,
|
|
3196
|
+
max_body_size=max_body_size,
|
|
3197
|
+
logfire_instance=self,
|
|
3198
|
+
)
|
|
3199
|
+
|
|
3200
|
+
|
|
3201
|
+
class FastLogfireSpan:
|
|
3202
|
+
"""A simple version of `LogfireSpan` optimized for auto-tracing."""
|
|
3203
|
+
|
|
3204
|
+
__slots__ = ('_span', '_token')
|
|
3205
|
+
|
|
3206
|
+
def __init__(self, span: trace_api.Span) -> None:
|
|
3207
|
+
self._span = span
|
|
3208
|
+
self._token = context_api.attach(trace_api.set_span_in_context(self._span))
|
|
3209
|
+
|
|
3210
|
+
def __enter__(self) -> FastLogfireSpan:
|
|
3211
|
+
return self
|
|
3212
|
+
|
|
3213
|
+
@handle_internal_errors
|
|
3214
|
+
def __exit__(self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: Any) -> None:
|
|
3215
|
+
context_api.detach(self._token)
|
|
3216
|
+
self._span.__exit__(exc_type, exc_value, traceback)
|
|
3217
|
+
|
|
3218
|
+
|
|
3219
|
+
# Changes to this class may need to be reflected in `FastLogfireSpan` and `NoopSpan` as well.
|
|
3220
|
+
class LogfireSpan(ReadableSpan):
|
|
3221
|
+
def __init__(
|
|
3222
|
+
self,
|
|
3223
|
+
span_name: str,
|
|
3224
|
+
otlp_attributes: dict[str, otel_types.AttributeValue],
|
|
3225
|
+
tracer: _ProxyTracer,
|
|
3226
|
+
json_schema_properties: JsonSchemaProperties,
|
|
3227
|
+
links: Sequence[tuple[SpanContext, otel_types.Attributes]],
|
|
3228
|
+
span_kind: SpanKind = SpanKind.INTERNAL,
|
|
3229
|
+
) -> None:
|
|
3230
|
+
self._span_name = span_name
|
|
3231
|
+
self._otlp_attributes = otlp_attributes
|
|
3232
|
+
self._tracer = tracer
|
|
3233
|
+
self._json_schema_properties = json_schema_properties
|
|
3234
|
+
self._links = list(trace_api.Link(context=context, attributes=attributes) for context, attributes in links)
|
|
3235
|
+
self._span_kind = span_kind
|
|
3236
|
+
|
|
3237
|
+
self._added_attributes = False
|
|
3238
|
+
self._token: None | Token[Context] = None
|
|
3239
|
+
self._span: None | _LogfireWrappedSpan = None
|
|
3240
|
+
|
|
3241
|
+
if not TYPE_CHECKING: # pragma: no branch
|
|
3242
|
+
|
|
3243
|
+
def __getattr__(self, name: str) -> Any:
|
|
3244
|
+
return getattr(self._span, name)
|
|
3245
|
+
|
|
3246
|
+
@handle_internal_errors
|
|
3247
|
+
def _start(self):
|
|
3248
|
+
if self._span is not None:
|
|
3249
|
+
return
|
|
3250
|
+
self._span = self._tracer.start_span(
|
|
3251
|
+
name=self._span_name,
|
|
3252
|
+
attributes=self._otlp_attributes,
|
|
3253
|
+
links=self._links,
|
|
3254
|
+
kind=self._span_kind,
|
|
3255
|
+
)
|
|
3256
|
+
|
|
3257
|
+
@handle_internal_errors
|
|
3258
|
+
def _attach(self):
|
|
3259
|
+
if self._token is not None:
|
|
3260
|
+
return
|
|
3261
|
+
assert self._span is not None
|
|
3262
|
+
self._token = context_api.attach(trace_api.set_span_in_context(self._span))
|
|
3263
|
+
|
|
3264
|
+
def __enter__(self) -> LogfireSpan:
|
|
3265
|
+
self._start()
|
|
3266
|
+
self._attach()
|
|
3267
|
+
return self
|
|
3268
|
+
|
|
3269
|
+
@handle_internal_errors
|
|
3270
|
+
def _end(self):
|
|
3271
|
+
if not self._span or not self._span.is_recording():
|
|
3272
|
+
return
|
|
3273
|
+
if self._added_attributes:
|
|
3274
|
+
self._span.set_attribute(ATTRIBUTES_JSON_SCHEMA_KEY, attributes_json_schema(self._json_schema_properties))
|
|
3275
|
+
self._span.end()
|
|
3276
|
+
|
|
3277
|
+
def _detach(self):
|
|
3278
|
+
if self._token is None:
|
|
3279
|
+
return
|
|
3280
|
+
context_api.detach(self._token)
|
|
3281
|
+
self._token = None
|
|
3282
|
+
|
|
3283
|
+
@handle_internal_errors
|
|
3284
|
+
def __exit__(self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: Any) -> None:
|
|
3285
|
+
self._detach()
|
|
3286
|
+
if self._span and self._span.is_recording() and isinstance(exc_value, BaseException):
|
|
3287
|
+
self._span.record_exception(exc_value, escaped=True)
|
|
3288
|
+
self._end()
|
|
3289
|
+
|
|
3290
|
+
@property
|
|
3291
|
+
def message_template(self) -> str | None: # pragma: no cover
|
|
3292
|
+
return self._get_attribute(ATTRIBUTES_MESSAGE_TEMPLATE_KEY, None)
|
|
3293
|
+
|
|
3294
|
+
@property
|
|
3295
|
+
def tags(self) -> tuple[str, ...]:
|
|
3296
|
+
return self._get_attribute(ATTRIBUTES_TAGS_KEY, ())
|
|
3297
|
+
|
|
3298
|
+
@tags.setter
|
|
3299
|
+
@handle_internal_errors
|
|
3300
|
+
def tags(self, new_tags: Sequence[str]) -> None:
|
|
3301
|
+
"""Set or add tags to the span."""
|
|
3302
|
+
if isinstance(new_tags, str):
|
|
3303
|
+
new_tags = (new_tags,)
|
|
3304
|
+
self._set_attribute(ATTRIBUTES_TAGS_KEY, tuple(uniquify_sequence(new_tags)))
|
|
3305
|
+
|
|
3306
|
+
@property
|
|
3307
|
+
def message(self) -> str:
|
|
3308
|
+
return self._get_attribute(ATTRIBUTES_MESSAGE_KEY, self._span_name)
|
|
3309
|
+
|
|
3310
|
+
@message.setter
|
|
3311
|
+
def message(self, message: str):
|
|
3312
|
+
self._set_attribute(ATTRIBUTES_MESSAGE_KEY, message)
|
|
3313
|
+
|
|
3314
|
+
@handle_internal_errors
|
|
3315
|
+
def set_attribute(self, key: str, value: Any) -> None:
|
|
3316
|
+
"""Sets an attribute on the span.
|
|
3317
|
+
|
|
3318
|
+
Args:
|
|
3319
|
+
key: The key of the attribute.
|
|
3320
|
+
value: The value of the attribute.
|
|
3321
|
+
"""
|
|
3322
|
+
self._added_attributes = True
|
|
3323
|
+
self._json_schema_properties[key] = create_json_schema(value, set())
|
|
3324
|
+
otel_value = self._otlp_attributes[key] = prepare_otlp_attribute(value)
|
|
3325
|
+
if self._span is not None: # pragma: no branch
|
|
3326
|
+
self._span.set_attribute(key, otel_value)
|
|
3327
|
+
|
|
3328
|
+
def set_attributes(self, attributes: dict[str, Any]) -> None:
|
|
3329
|
+
"""Sets the given attributes on the span."""
|
|
3330
|
+
for key, value in attributes.items():
|
|
3331
|
+
self.set_attribute(key, value)
|
|
3332
|
+
|
|
3333
|
+
def add_link(self, context: SpanContext, attributes: otel_types.Attributes = None) -> None:
|
|
3334
|
+
if self._span is None:
|
|
3335
|
+
self._links += [trace_api.Link(context=context, attributes=attributes)]
|
|
3336
|
+
else:
|
|
3337
|
+
self._span.add_link(context, attributes)
|
|
3338
|
+
|
|
3339
|
+
# TODO(Marcelo): We should add a test for `record_exception`.
|
|
3340
|
+
def record_exception(
|
|
3341
|
+
self,
|
|
3342
|
+
exception: BaseException,
|
|
3343
|
+
attributes: otel_types.Attributes = None,
|
|
3344
|
+
timestamp: int | None = None,
|
|
3345
|
+
escaped: bool = False,
|
|
3346
|
+
) -> None: # pragma: no cover
|
|
3347
|
+
"""Records an exception as a span event.
|
|
3348
|
+
|
|
3349
|
+
Delegates to the OpenTelemetry SDK `Span.record_exception` method.
|
|
3350
|
+
"""
|
|
3351
|
+
if self._span is None:
|
|
3352
|
+
raise RuntimeError('Span has not been started')
|
|
3353
|
+
|
|
3354
|
+
self._span.record_exception(
|
|
3355
|
+
exception,
|
|
3356
|
+
attributes=attributes,
|
|
3357
|
+
timestamp=timestamp,
|
|
3358
|
+
escaped=escaped,
|
|
3359
|
+
)
|
|
3360
|
+
|
|
3361
|
+
def is_recording(self) -> bool:
|
|
3362
|
+
return self._span is not None and self._span.is_recording()
|
|
3363
|
+
|
|
3364
|
+
@handle_internal_errors
|
|
3365
|
+
def set_level(self, level: LevelName | int):
|
|
3366
|
+
"""Set the log level of this span."""
|
|
3367
|
+
attributes = log_level_attributes(level)
|
|
3368
|
+
if self._span is None:
|
|
3369
|
+
self._otlp_attributes.update(attributes)
|
|
3370
|
+
else:
|
|
3371
|
+
self._span.set_attributes(attributes)
|
|
3372
|
+
|
|
3373
|
+
def _get_attribute(self, key: str, default: Any) -> Any:
|
|
3374
|
+
attributes = getattr(self._span, 'attributes', self._otlp_attributes)
|
|
3375
|
+
return attributes.get(key, default)
|
|
3376
|
+
|
|
3377
|
+
def _set_attribute(self, key: str, value: Any) -> None:
|
|
3378
|
+
"""Set an attribute on the span or in the _otlp_attributes if span is not yet created."""
|
|
3379
|
+
if self._span is None:
|
|
3380
|
+
self._otlp_attributes[key] = value
|
|
3381
|
+
else:
|
|
3382
|
+
self._span.set_attribute(key, value)
|
|
3383
|
+
|
|
3384
|
+
|
|
3385
|
+
class NoopSpan:
|
|
3386
|
+
"""Implements the same methods as `LogfireSpan` but does nothing.
|
|
3387
|
+
|
|
3388
|
+
Used in place of `LogfireSpan` and `FastLogfireSpan` when an exception occurs during span creation.
|
|
3389
|
+
This way code like:
|
|
3390
|
+
|
|
3391
|
+
with logfire.span(...) as span:
|
|
3392
|
+
span.set_attribute(...)
|
|
3393
|
+
|
|
3394
|
+
doesn't raise an error even if `logfire.span` fails internally.
|
|
3395
|
+
If `logfire.span` just returned `None` then the `with` block and the `span.set_attribute` call would raise an error.
|
|
3396
|
+
|
|
3397
|
+
TODO this should also be used when tracing is disabled, e.g. before `logfire.configure()` has been called.
|
|
3398
|
+
"""
|
|
3399
|
+
|
|
3400
|
+
def __init__(self, *_args: Any, **__kwargs: Any) -> None:
|
|
3401
|
+
pass
|
|
3402
|
+
|
|
3403
|
+
def __getattr__(self, _name: str) -> Any:
|
|
3404
|
+
# Handle methods of LogfireSpan which return nothing
|
|
3405
|
+
return lambda *_args, **__kwargs: None # pyright: ignore[reportUnknownVariableType, reportUnknownLambdaType]
|
|
3406
|
+
|
|
3407
|
+
def __enter__(self) -> NoopSpan:
|
|
3408
|
+
return self
|
|
3409
|
+
|
|
3410
|
+
def __exit__(self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: Any) -> None:
|
|
3411
|
+
pass
|
|
3412
|
+
|
|
3413
|
+
# Implement methods/properties that return something to get the type right.
|
|
3414
|
+
@property
|
|
3415
|
+
def message_template(self) -> str: # pragma: no cover
|
|
3416
|
+
return ''
|
|
3417
|
+
|
|
3418
|
+
@property
|
|
3419
|
+
def tags(self) -> tuple[str, ...]:
|
|
3420
|
+
return ()
|
|
3421
|
+
|
|
3422
|
+
# This is required to make `span.tags = ` not raise an error.
|
|
3423
|
+
@tags.setter
|
|
3424
|
+
def tags(self, new_tags: Sequence[str]) -> None:
|
|
3425
|
+
pass
|
|
3426
|
+
|
|
3427
|
+
@property
|
|
3428
|
+
def message(self) -> str: # pragma: no cover
|
|
3429
|
+
return ''
|
|
3430
|
+
|
|
3431
|
+
# This is required to make `span.message = ` not raise an error.
|
|
3432
|
+
@message.setter
|
|
3433
|
+
def message(self, message: str):
|
|
3434
|
+
pass
|
|
3435
|
+
|
|
3436
|
+
@property
|
|
3437
|
+
def _span(self) -> Any:
|
|
3438
|
+
return trace_api.INVALID_SPAN
|
|
3439
|
+
|
|
3440
|
+
def is_recording(self) -> bool:
|
|
3441
|
+
return False
|
|
3442
|
+
|
|
3443
|
+
|
|
3444
|
+
AttributesValueType = TypeVar('AttributesValueType', bound=Any | otel_types.AttributeValue)
|
|
3445
|
+
|
|
3446
|
+
|
|
3447
|
+
def prepare_otlp_attributes(attributes: dict[str, Any]) -> dict[str, otel_types.AttributeValue]:
|
|
3448
|
+
"""Prepare attributes for sending to OpenTelemetry.
|
|
3449
|
+
|
|
3450
|
+
This will convert any non-OpenTelemetry compatible types to JSON.
|
|
3451
|
+
"""
|
|
3452
|
+
return {key: prepare_otlp_attribute(value) for key, value in attributes.items()}
|
|
3453
|
+
|
|
3454
|
+
|
|
3455
|
+
def prepare_otlp_attribute(value: Any) -> otel_types.AttributeValue:
|
|
3456
|
+
"""Convert a user attribute to an OpenTelemetry compatible type."""
|
|
3457
|
+
if isinstance(value, Enum):
|
|
3458
|
+
return logfire_json_dumps(value)
|
|
3459
|
+
elif isinstance(value, int):
|
|
3460
|
+
if not -OTLP_MAX_INT_SIZE - 1 <= value <= OTLP_MAX_INT_SIZE:
|
|
3461
|
+
warnings.warn(
|
|
3462
|
+
f'Integer value {value} is outside the range of OTLP integers (signed 64-bit), '
|
|
3463
|
+
'so it will be sent as a string. '
|
|
3464
|
+
'If you need support for sending such integers, please open a feature request',
|
|
3465
|
+
UserWarning,
|
|
3466
|
+
)
|
|
3467
|
+
return str(value)
|
|
3468
|
+
else:
|
|
3469
|
+
return value
|
|
3470
|
+
elif isinstance(value, float):
|
|
3471
|
+
if not math.isfinite(value):
|
|
3472
|
+
return str(value)
|
|
3473
|
+
return value
|
|
3474
|
+
elif isinstance(value, (str, bool)):
|
|
3475
|
+
return value
|
|
3476
|
+
else:
|
|
3477
|
+
return logfire_json_dumps(value)
|
|
3478
|
+
|
|
3479
|
+
|
|
3480
|
+
def set_user_attributes_on_raw_span(span: Span, attributes: dict[str, Any]) -> None:
|
|
3481
|
+
if not span.is_recording():
|
|
3482
|
+
return
|
|
3483
|
+
|
|
3484
|
+
otlp_attributes = prepare_otlp_attributes(attributes)
|
|
3485
|
+
if json_schema_properties := attributes_json_schema_properties(attributes): # pragma: no branch
|
|
3486
|
+
existing_properties = JsonSchemaProperties({})
|
|
3487
|
+
existing_json_schema_str = (span.attributes or {}).get(ATTRIBUTES_JSON_SCHEMA_KEY)
|
|
3488
|
+
if existing_json_schema_str and isinstance(existing_json_schema_str, str):
|
|
3489
|
+
with contextlib.suppress(json.JSONDecodeError):
|
|
3490
|
+
existing_json_schema = json.loads(existing_json_schema_str)
|
|
3491
|
+
existing_properties = existing_json_schema.get('properties', {})
|
|
3492
|
+
existing_properties.update(json_schema_properties)
|
|
3493
|
+
otlp_attributes[ATTRIBUTES_JSON_SCHEMA_KEY] = attributes_json_schema(existing_properties)
|
|
3494
|
+
span.set_attributes(otlp_attributes)
|
|
3495
|
+
|
|
3496
|
+
|
|
3497
|
+
P = ParamSpec('P')
|
|
3498
|
+
R = TypeVar('R')
|