struct-sdk 0.4.17__tar.gz → 0.4.22__tar.gz
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.
- {struct_sdk-0.4.17 → struct_sdk-0.4.22}/PKG-INFO +37 -12
- {struct_sdk-0.4.17 → struct_sdk-0.4.22}/README.md +36 -11
- {struct_sdk-0.4.17 → struct_sdk-0.4.22}/pyproject.toml +4 -1
- {struct_sdk-0.4.17 → struct_sdk-0.4.22}/src/struct_sdk/__init__.py +2 -1
- {struct_sdk-0.4.17 → struct_sdk-0.4.22}/src/struct_sdk/_auto.py +77 -17
- struct_sdk-0.4.22/src/struct_sdk/_container.py +271 -0
- struct_sdk-0.4.22/src/struct_sdk/_event_loop.py +194 -0
- struct_sdk-0.4.22/src/struct_sdk/_metrics.py +217 -0
- struct_sdk-0.4.22/src/struct_sdk/_pool.py +426 -0
- {struct_sdk-0.4.17 → struct_sdk-0.4.22}/src/struct_sdk/core.py +160 -14
- {struct_sdk-0.4.17 → struct_sdk-0.4.22}/src/struct_sdk/pydantic_ai.py +19 -14
- {struct_sdk-0.4.17 → struct_sdk-0.4.22}/src/struct_sdk/temporal.py +72 -14
- {struct_sdk-0.4.17 → struct_sdk-0.4.22}/.gitignore +0 -0
- {struct_sdk-0.4.17 → struct_sdk-0.4.22}/LICENSE +0 -0
- {struct_sdk-0.4.17 → struct_sdk-0.4.22}/src/struct_sdk/_distro.py +0 -0
- {struct_sdk-0.4.17 → struct_sdk-0.4.22}/src/struct_sdk/_genai_content.py +0 -0
- {struct_sdk-0.4.17 → struct_sdk-0.4.22}/src/struct_sdk/_operation_details.py +0 -0
- {struct_sdk-0.4.17 → struct_sdk-0.4.22}/src/struct_sdk/ag2.py +0 -0
- {struct_sdk-0.4.17 → struct_sdk-0.4.22}/src/struct_sdk/anthropic.py +0 -0
- {struct_sdk-0.4.17 → struct_sdk-0.4.22}/src/struct_sdk/autogen.py +0 -0
- {struct_sdk-0.4.17 → struct_sdk-0.4.22}/src/struct_sdk/claude_agent.py +0 -0
- {struct_sdk-0.4.17 → struct_sdk-0.4.22}/src/struct_sdk/crewai.py +0 -0
- {struct_sdk-0.4.17 → struct_sdk-0.4.22}/src/struct_sdk/gcp.py +0 -0
- {struct_sdk-0.4.17 → struct_sdk-0.4.22}/src/struct_sdk/google_genai.py +0 -0
- {struct_sdk-0.4.17 → struct_sdk-0.4.22}/src/struct_sdk/langchain.py +0 -0
- {struct_sdk-0.4.17 → struct_sdk-0.4.22}/src/struct_sdk/litellm.py +0 -0
- {struct_sdk-0.4.17 → struct_sdk-0.4.22}/src/struct_sdk/llamaindex.py +0 -0
- {struct_sdk-0.4.17 → struct_sdk-0.4.22}/src/struct_sdk/mcp.py +0 -0
- {struct_sdk-0.4.17 → struct_sdk-0.4.22}/src/struct_sdk/openai.py +0 -0
- {struct_sdk-0.4.17 → struct_sdk-0.4.22}/src/struct_sdk/openai_agents.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: struct-sdk
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.22
|
|
4
4
|
Summary: Struct agent observability SDK — auto-instruments AI agent frameworks with OpenTelemetry
|
|
5
5
|
Project-URL: Homepage, https://struct.ai
|
|
6
6
|
Project-URL: Documentation, https://struct.ai/docs
|
|
@@ -806,9 +806,14 @@ pass it: `OTEL_SERVICE_NAME`, and `service.version` and
|
|
|
806
806
|
`deployment.environment` in `OTEL_RESOURCE_ATTRIBUTES`. Arguments to `init()`
|
|
807
807
|
win. The resource also carries host, runtime and (with the `[auto]` extra)
|
|
808
808
|
container metadata, plus the commit when `STRUCT_GIT_COMMIT_SHA` and
|
|
809
|
-
`STRUCT_GIT_REPOSITORY_URL` are set.
|
|
810
|
-
|
|
811
|
-
|
|
809
|
+
`STRUCT_GIT_REPOSITORY_URL` are set. On Azure Container Apps it also carries
|
|
810
|
+
`cloud.platform`, `container_app`, `container_app_revision` and `replica`, read
|
|
811
|
+
from the variables the platform sets; when Struct attaches to your
|
|
812
|
+
OpenTelemetry setup, Struct's copy of your spans and logs, and the metrics
|
|
813
|
+
Struct's own readers export, get them too, while your own resource stays as
|
|
814
|
+
it is. It includes a
|
|
815
|
+
`service.instance.id` so replicas stay distinguishable; an ID from
|
|
816
|
+
`OTEL_RESOURCE_ATTRIBUTES` is preserved.
|
|
812
817
|
|
|
813
818
|
In pre-fork servers (for example `gunicorn --preload`), call `struct.init()` in
|
|
814
819
|
each worker (gunicorn's `post_fork` hook), not in the parent: forked workers
|
|
@@ -860,12 +865,12 @@ before `init()`, call the contrib instrumentor directly (for example
|
|
|
860
865
|
|---|---|
|
|
861
866
|
| Traces | Django, FastAPI, Flask, Starlette, Tornado, Falcon, Pyramid, aiohttp (client and server), requests, httpx, urllib, urllib3, gRPC, psycopg2, psycopg, aiopg, asyncpg, PyMySQL, MySQL Connector, mysqlclient, pymssql, sqlite3, PyMongo, Cassandra, Redis, pymemcache, Tortoise ORM, Celery, botocore, aiobotocore, Kafka (confluent-kafka, aiokafka, kafka-python), RabbitMQ (pika, aio-pika), Jinja2, Azure SDK. Work handed to threads and `ThreadPoolExecutor` stays in the caller's trace. SQLAlchemy is off by default because its query spans duplicate the database driver's; enable it with `{"sqlalchemy": {"enabled": True}}` if you prefer ORM-level spans. |
|
|
862
867
|
| Logs | Python `logging` records that reach the root logger, with trace context. The SDK's own and OpenTelemetry's records are excluded. With the `[structlog]` extra, structlog events that structlog writes itself (its default) are exported with their fields as attributes; events structlog hands to `logging` (`structlog.stdlib.LoggerFactory`) are exported once, through the `logging` bridge. Extras and structlog fields OpenTelemetry can't take as-is are exported as strings: dicts and mixed-type lists as JSON, everything else (UUIDs, datetimes, `None`, bytes) as its `str()`. Your other handlers still see the original values. With the `[exceptions]` extra, uncaught exceptions (main thread, other threads, asyncio) are exported as log records. If your app configures no logging, its warnings still print to stderr as they would without Struct. This is separate from `content_capture`, which only governs LLM content; disable `{"logging": {"enabled": False}}` and `{"structlog": {"enabled": False}}` (which also stops copies of your logs when Struct attaches to your OpenTelemetry setup), or redact attributes, if application logs can carry sensitive data. |
|
|
863
|
-
| Metrics | Instrumentor metrics (for example `http.server.duration`) and process metrics (`process.cpu.*`, `process.memory.*`, threads, file descriptors, GC). Counters and histograms use delta temporality. |
|
|
868
|
+
| Metrics | Instrumentor metrics (for example `http.server.duration`) and process metrics (`process.cpu.*`, `process.memory.*`, threads, file descriptors, GC). In a container, CPU and memory against the container's limits (`container.cpu.time`, `container.cpu.usage`, `container.memory.usage`, `container.memory.working_set`, `container.memory.available`, `struct.container.cpu.limit`, `struct.container.memory.limit`). For asyncio apps, the largest event-loop delay per minute (`struct.asyncio.eventloop.delay.max`). For SQLAlchemy, each connection pool's used and idle connections, limits and checkout time (`db.client.connection.count`, `.max`, `.idle.max`, `.use_time`), from SQLAlchemy's own pool events. Counters and histograms use delta temporality. Turn Struct's own metrics off with `{"metrics": {"enabled": False}}`. |
|
|
864
869
|
|
|
865
870
|
AWS calls through boto3/botocore or aiobotocore become one span per API
|
|
866
871
|
operation (for example `S3.PutObject`), retries included, and carry the X-Ray
|
|
867
872
|
header AWS services propagate. When Struct attaches to your existing
|
|
868
|
-
OpenTelemetry setup, it instruments
|
|
873
|
+
OpenTelemetry setup, it instruments no library, so AWS operation spans reach
|
|
869
874
|
Struct only if your setup instruments botocore itself.
|
|
870
875
|
|
|
871
876
|
Each instrumentor activates only when its library is installed.
|
|
@@ -891,12 +896,26 @@ precedence over it.
|
|
|
891
896
|
Full-app mode installs Struct's providers as the global OpenTelemetry
|
|
892
897
|
providers only when no tracer, meter or logger provider is installed. If the
|
|
893
898
|
process already configured any of them (Azure Monitor, your own SDK setup),
|
|
894
|
-
Struct adds its exporters to your SDK tracer and logger providers and
|
|
895
|
-
|
|
896
|
-
|
|
899
|
+
Struct adds its exporters to your SDK tracer and logger providers and one
|
|
900
|
+
metric reader to your SDK meter provider, and instruments no library: your
|
|
901
|
+
setup keeps ownership of instrumentation, sampling and shutdown. Struct's own
|
|
902
|
+
container and event-loop metrics run on a meter provider of Struct's that is
|
|
903
|
+
never global, so nothing new reaches your own backend. Struct's own GenAI
|
|
897
904
|
spans keep their isolated provider either way, so your sampler does not drop
|
|
898
905
|
them.
|
|
899
906
|
|
|
907
|
+
Adding a reader to an existing meter provider needs opentelemetry-sdk 1.43 or
|
|
908
|
+
later. On an older SDK, Struct logs one warning and your metrics are not sent
|
|
909
|
+
to Struct unless you pass its reader when you build your provider:
|
|
910
|
+
|
|
911
|
+
```python
|
|
912
|
+
import struct_sdk
|
|
913
|
+
from azure.monitor.opentelemetry import configure_azure_monitor
|
|
914
|
+
|
|
915
|
+
configure_azure_monitor(metric_readers=[struct_sdk.metric_reader(ingest_key="pk-...")])
|
|
916
|
+
struct_sdk.struct.init(ingest_key="pk-...") # sees the reader and adds no second one
|
|
917
|
+
```
|
|
918
|
+
|
|
900
919
|
### Datadog ddtrace
|
|
901
920
|
|
|
902
921
|
Under `ddtrace-run`, Struct leaves the libraries ddtrace patches to it, and
|
|
@@ -951,9 +970,15 @@ client = await Client.connect(
|
|
|
951
970
|
```
|
|
952
971
|
|
|
953
972
|
`telemetry_config()` exports Temporal Core metrics (task slots,
|
|
954
|
-
schedule-to-start latency, poll results, sticky cache) to Struct.
|
|
955
|
-
|
|
956
|
-
|
|
973
|
+
schedule-to-start latency, poll results, sticky cache) to Struct. Core's own
|
|
974
|
+
log lines, at Temporal's default levels, go to the Python logger
|
|
975
|
+
`temporalio.core` instead of Core's console, so they follow your logging setup
|
|
976
|
+
and reach Struct through its log bridge (full-app mode adds one; when Struct
|
|
977
|
+
attaches to your OpenTelemetry, your own bridge carries them); failed metric
|
|
978
|
+
exports are not logged. Pass
|
|
979
|
+
`forward_core_logs=False` to keep Core's console output, or `core_logger=` to
|
|
980
|
+
choose the logger. If you build your own `TelemetryConfig`, pass
|
|
981
|
+
`logging=temporal.logging_config()` for the same logging. `tracing_interceptor()` (temporalio 1.11+) traces
|
|
957
982
|
workflows and activities with Struct's tracer; a failing span processor never
|
|
958
983
|
blocks a Temporal call or replaces its exception.
|
|
959
984
|
Temporal server metrics are a Prometheus endpoint; scrape them with an
|
|
@@ -690,9 +690,14 @@ pass it: `OTEL_SERVICE_NAME`, and `service.version` and
|
|
|
690
690
|
`deployment.environment` in `OTEL_RESOURCE_ATTRIBUTES`. Arguments to `init()`
|
|
691
691
|
win. The resource also carries host, runtime and (with the `[auto]` extra)
|
|
692
692
|
container metadata, plus the commit when `STRUCT_GIT_COMMIT_SHA` and
|
|
693
|
-
`STRUCT_GIT_REPOSITORY_URL` are set.
|
|
694
|
-
|
|
695
|
-
|
|
693
|
+
`STRUCT_GIT_REPOSITORY_URL` are set. On Azure Container Apps it also carries
|
|
694
|
+
`cloud.platform`, `container_app`, `container_app_revision` and `replica`, read
|
|
695
|
+
from the variables the platform sets; when Struct attaches to your
|
|
696
|
+
OpenTelemetry setup, Struct's copy of your spans and logs, and the metrics
|
|
697
|
+
Struct's own readers export, get them too, while your own resource stays as
|
|
698
|
+
it is. It includes a
|
|
699
|
+
`service.instance.id` so replicas stay distinguishable; an ID from
|
|
700
|
+
`OTEL_RESOURCE_ATTRIBUTES` is preserved.
|
|
696
701
|
|
|
697
702
|
In pre-fork servers (for example `gunicorn --preload`), call `struct.init()` in
|
|
698
703
|
each worker (gunicorn's `post_fork` hook), not in the parent: forked workers
|
|
@@ -744,12 +749,12 @@ before `init()`, call the contrib instrumentor directly (for example
|
|
|
744
749
|
|---|---|
|
|
745
750
|
| Traces | Django, FastAPI, Flask, Starlette, Tornado, Falcon, Pyramid, aiohttp (client and server), requests, httpx, urllib, urllib3, gRPC, psycopg2, psycopg, aiopg, asyncpg, PyMySQL, MySQL Connector, mysqlclient, pymssql, sqlite3, PyMongo, Cassandra, Redis, pymemcache, Tortoise ORM, Celery, botocore, aiobotocore, Kafka (confluent-kafka, aiokafka, kafka-python), RabbitMQ (pika, aio-pika), Jinja2, Azure SDK. Work handed to threads and `ThreadPoolExecutor` stays in the caller's trace. SQLAlchemy is off by default because its query spans duplicate the database driver's; enable it with `{"sqlalchemy": {"enabled": True}}` if you prefer ORM-level spans. |
|
|
746
751
|
| Logs | Python `logging` records that reach the root logger, with trace context. The SDK's own and OpenTelemetry's records are excluded. With the `[structlog]` extra, structlog events that structlog writes itself (its default) are exported with their fields as attributes; events structlog hands to `logging` (`structlog.stdlib.LoggerFactory`) are exported once, through the `logging` bridge. Extras and structlog fields OpenTelemetry can't take as-is are exported as strings: dicts and mixed-type lists as JSON, everything else (UUIDs, datetimes, `None`, bytes) as its `str()`. Your other handlers still see the original values. With the `[exceptions]` extra, uncaught exceptions (main thread, other threads, asyncio) are exported as log records. If your app configures no logging, its warnings still print to stderr as they would without Struct. This is separate from `content_capture`, which only governs LLM content; disable `{"logging": {"enabled": False}}` and `{"structlog": {"enabled": False}}` (which also stops copies of your logs when Struct attaches to your OpenTelemetry setup), or redact attributes, if application logs can carry sensitive data. |
|
|
747
|
-
| Metrics | Instrumentor metrics (for example `http.server.duration`) and process metrics (`process.cpu.*`, `process.memory.*`, threads, file descriptors, GC). Counters and histograms use delta temporality. |
|
|
752
|
+
| Metrics | Instrumentor metrics (for example `http.server.duration`) and process metrics (`process.cpu.*`, `process.memory.*`, threads, file descriptors, GC). In a container, CPU and memory against the container's limits (`container.cpu.time`, `container.cpu.usage`, `container.memory.usage`, `container.memory.working_set`, `container.memory.available`, `struct.container.cpu.limit`, `struct.container.memory.limit`). For asyncio apps, the largest event-loop delay per minute (`struct.asyncio.eventloop.delay.max`). For SQLAlchemy, each connection pool's used and idle connections, limits and checkout time (`db.client.connection.count`, `.max`, `.idle.max`, `.use_time`), from SQLAlchemy's own pool events. Counters and histograms use delta temporality. Turn Struct's own metrics off with `{"metrics": {"enabled": False}}`. |
|
|
748
753
|
|
|
749
754
|
AWS calls through boto3/botocore or aiobotocore become one span per API
|
|
750
755
|
operation (for example `S3.PutObject`), retries included, and carry the X-Ray
|
|
751
756
|
header AWS services propagate. When Struct attaches to your existing
|
|
752
|
-
OpenTelemetry setup, it instruments
|
|
757
|
+
OpenTelemetry setup, it instruments no library, so AWS operation spans reach
|
|
753
758
|
Struct only if your setup instruments botocore itself.
|
|
754
759
|
|
|
755
760
|
Each instrumentor activates only when its library is installed.
|
|
@@ -775,12 +780,26 @@ precedence over it.
|
|
|
775
780
|
Full-app mode installs Struct's providers as the global OpenTelemetry
|
|
776
781
|
providers only when no tracer, meter or logger provider is installed. If the
|
|
777
782
|
process already configured any of them (Azure Monitor, your own SDK setup),
|
|
778
|
-
Struct adds its exporters to your SDK tracer and logger providers and
|
|
779
|
-
|
|
780
|
-
|
|
783
|
+
Struct adds its exporters to your SDK tracer and logger providers and one
|
|
784
|
+
metric reader to your SDK meter provider, and instruments no library: your
|
|
785
|
+
setup keeps ownership of instrumentation, sampling and shutdown. Struct's own
|
|
786
|
+
container and event-loop metrics run on a meter provider of Struct's that is
|
|
787
|
+
never global, so nothing new reaches your own backend. Struct's own GenAI
|
|
781
788
|
spans keep their isolated provider either way, so your sampler does not drop
|
|
782
789
|
them.
|
|
783
790
|
|
|
791
|
+
Adding a reader to an existing meter provider needs opentelemetry-sdk 1.43 or
|
|
792
|
+
later. On an older SDK, Struct logs one warning and your metrics are not sent
|
|
793
|
+
to Struct unless you pass its reader when you build your provider:
|
|
794
|
+
|
|
795
|
+
```python
|
|
796
|
+
import struct_sdk
|
|
797
|
+
from azure.monitor.opentelemetry import configure_azure_monitor
|
|
798
|
+
|
|
799
|
+
configure_azure_monitor(metric_readers=[struct_sdk.metric_reader(ingest_key="pk-...")])
|
|
800
|
+
struct_sdk.struct.init(ingest_key="pk-...") # sees the reader and adds no second one
|
|
801
|
+
```
|
|
802
|
+
|
|
784
803
|
### Datadog ddtrace
|
|
785
804
|
|
|
786
805
|
Under `ddtrace-run`, Struct leaves the libraries ddtrace patches to it, and
|
|
@@ -835,9 +854,15 @@ client = await Client.connect(
|
|
|
835
854
|
```
|
|
836
855
|
|
|
837
856
|
`telemetry_config()` exports Temporal Core metrics (task slots,
|
|
838
|
-
schedule-to-start latency, poll results, sticky cache) to Struct.
|
|
839
|
-
|
|
840
|
-
|
|
857
|
+
schedule-to-start latency, poll results, sticky cache) to Struct. Core's own
|
|
858
|
+
log lines, at Temporal's default levels, go to the Python logger
|
|
859
|
+
`temporalio.core` instead of Core's console, so they follow your logging setup
|
|
860
|
+
and reach Struct through its log bridge (full-app mode adds one; when Struct
|
|
861
|
+
attaches to your OpenTelemetry, your own bridge carries them); failed metric
|
|
862
|
+
exports are not logged. Pass
|
|
863
|
+
`forward_core_logs=False` to keep Core's console output, or `core_logger=` to
|
|
864
|
+
choose the logger. If you build your own `TelemetryConfig`, pass
|
|
865
|
+
`logging=temporal.logging_config()` for the same logging. `tracing_interceptor()` (temporalio 1.11+) traces
|
|
841
866
|
workflows and activities with Struct's tracer; a failing span processor never
|
|
842
867
|
blocks a Temporal call or replaces its exception.
|
|
843
868
|
Temporal server metrics are a Prometheus endpoint; scrape them with an
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "struct-sdk"
|
|
7
|
-
version = "0.4.
|
|
7
|
+
version = "0.4.22"
|
|
8
8
|
description = "Struct agent observability SDK — auto-instruments AI agent frameworks with OpenTelemetry"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.10"
|
|
@@ -178,6 +178,9 @@ test = [
|
|
|
178
178
|
"opentelemetry-instrumentation-threading",
|
|
179
179
|
"opentelemetry-instrumentation-exceptions",
|
|
180
180
|
"opentelemetry-instrumentation-sqlite3",
|
|
181
|
+
# Connection-pool metrics run against real SQLAlchemy pools, sync and async.
|
|
182
|
+
"sqlalchemy[asyncio]>=2.0",
|
|
183
|
+
"aiosqlite>=0.20",
|
|
181
184
|
# Zero-code activation is tested next to the standard distro's configurator.
|
|
182
185
|
"opentelemetry-distro",
|
|
183
186
|
"temporalio>=1.11.0",
|
|
@@ -7,8 +7,9 @@ Usage:
|
|
|
7
7
|
# Then use your agent framework as normal — telemetry is captured automatically.
|
|
8
8
|
"""
|
|
9
9
|
|
|
10
|
+
from struct_sdk._metrics import metric_reader
|
|
10
11
|
from struct_sdk.core import ContentCaptureMode, StructSDK
|
|
11
12
|
|
|
12
13
|
struct = StructSDK()
|
|
13
14
|
|
|
14
|
-
__all__ = ["struct", "ContentCaptureMode"]
|
|
15
|
+
__all__ = ["struct", "ContentCaptureMode", "metric_reader"]
|
|
@@ -10,8 +10,12 @@ Ownership follows the host's global providers:
|
|
|
10
10
|
* No tracer, meter or logger provider installed: Struct installs its
|
|
11
11
|
providers globally and instruments supported libraries.
|
|
12
12
|
* Any provider installed (Azure Monitor, the host's own OpenTelemetry): Struct
|
|
13
|
-
adds its exporters to the host's SDK tracer and
|
|
14
|
-
instruments
|
|
13
|
+
adds its exporters to the host's SDK tracer, logger and meter providers, if
|
|
14
|
+
any, and instruments no library — the host owns instrumentation, sampling and
|
|
15
|
+
lifecycle.
|
|
16
|
+
|
|
17
|
+
In either mode Struct's own metrics (container CPU and memory, event-loop
|
|
18
|
+
delay) run on a Struct-only meter provider that is never installed globally.
|
|
15
19
|
|
|
16
20
|
Pre-fork servers must call ``struct.init()`` in each worker: the instance id
|
|
17
21
|
and process metrics bind to the process that ran it.
|
|
@@ -38,11 +42,12 @@ from opentelemetry.sdk._logs import LoggerProvider, LogRecordProcessor
|
|
|
38
42
|
from opentelemetry.sdk.metrics import MeterProvider
|
|
39
43
|
from opentelemetry.sdk.trace import SpanProcessor, TracerProvider
|
|
40
44
|
|
|
45
|
+
from struct_sdk import _metrics
|
|
41
46
|
from struct_sdk.core import (
|
|
42
47
|
_body_value,
|
|
43
48
|
_contain_logged,
|
|
44
49
|
_log_processor,
|
|
45
|
-
|
|
50
|
+
_new_metric_reader,
|
|
46
51
|
_safe,
|
|
47
52
|
_span_processor,
|
|
48
53
|
)
|
|
@@ -170,6 +175,9 @@ class _NoPropagation(TextMapPropagator):
|
|
|
170
175
|
# Non-entry-point options handled here rather than by a contrib instrumentor.
|
|
171
176
|
LOGGING = "logging"
|
|
172
177
|
AZURE_SDK = "azure_sdk"
|
|
178
|
+
# Struct's metric reader on a host provider and Struct's own container and
|
|
179
|
+
# event-loop instruments.
|
|
180
|
+
METRICS = "metrics"
|
|
173
181
|
|
|
174
182
|
# Not ``exception``: it calls the module-level ``error`` (wrapped here), so a
|
|
175
183
|
# wrapper of its own would put two Struct frames under one record.
|
|
@@ -189,6 +197,11 @@ class FullAppState:
|
|
|
189
197
|
log_handler: Optional[logging.Handler] = None
|
|
190
198
|
restore_logging_config: Optional[Callable[[], None]] = None
|
|
191
199
|
host_processors: list[Any] = field(default_factory=list)
|
|
200
|
+
host_meter_provider: Optional[MeterProvider] = None
|
|
201
|
+
host_metric_reader: Optional[Any] = None
|
|
202
|
+
# The provider for Struct's own instruments, in either mode; never global.
|
|
203
|
+
struct_meter_provider: Optional[MeterProvider] = None
|
|
204
|
+
runtime: Optional[_metrics.RuntimeMetrics] = None
|
|
192
205
|
|
|
193
206
|
def shutdown(self, timeout_millis: int) -> None:
|
|
194
207
|
if self.restore_logging_config is not None:
|
|
@@ -201,6 +214,16 @@ class FullAppState:
|
|
|
201
214
|
# it log for every span the host ends afterwards.
|
|
202
215
|
for processor in self.host_processors:
|
|
203
216
|
processor.force_flush(timeout_millis)
|
|
217
|
+
runtime, self.runtime = self.runtime, None
|
|
218
|
+
if runtime is not None:
|
|
219
|
+
runtime.stop()
|
|
220
|
+
host, reader = self.host_meter_provider, self.host_metric_reader
|
|
221
|
+
self.host_meter_provider = self.host_metric_reader = None
|
|
222
|
+
if host is not None and reader is not None:
|
|
223
|
+
_metrics.detach_host_reader(host, reader, timeout_millis)
|
|
224
|
+
provider, self.struct_meter_provider = self.struct_meter_provider, None
|
|
225
|
+
if provider is not None and not getattr(provider, "_shutdown", False):
|
|
226
|
+
_contain_logged(lambda: _metrics.shut_down_once(provider, timeout_millis), site="auto.metrics.shutdown")
|
|
204
227
|
|
|
205
228
|
|
|
206
229
|
def enable(sdk: "StructSDK", options: Mapping[str, Mapping[str, Any]]) -> None:
|
|
@@ -223,8 +246,21 @@ def enable(sdk: "StructSDK", options: Mapping[str, Mapping[str, Any]]) -> None:
|
|
|
223
246
|
options = _with_env_disabled(options)
|
|
224
247
|
if host_has_providers:
|
|
225
248
|
budget = sdk._shutdown_timeout_seconds
|
|
249
|
+
if _enabled(options, METRICS):
|
|
250
|
+
def attach_metrics() -> None:
|
|
251
|
+
if isinstance(host_meter_provider, MeterProvider):
|
|
252
|
+
state.host_metric_reader = _metrics.attach_host_reader(host_meter_provider, sdk._endpoint, headers)
|
|
253
|
+
if state.host_metric_reader is not None:
|
|
254
|
+
state.host_meter_provider = host_meter_provider
|
|
255
|
+
_start_struct_metrics(state, sdk._endpoint, tracer_provider, headers)
|
|
256
|
+
|
|
257
|
+
_safe(attach_metrics, site="auto.metrics")
|
|
226
258
|
if isinstance(host_tracer_provider, TracerProvider):
|
|
227
|
-
processor = _HostAttachedSpanProcessor(
|
|
259
|
+
processor = _HostAttachedSpanProcessor(
|
|
260
|
+
_span_processor(sdk._endpoint, headers),
|
|
261
|
+
budget,
|
|
262
|
+
watch_loop=state.runtime.watch_running_loop if state.runtime is not None else None,
|
|
263
|
+
)
|
|
228
264
|
host_tracer_provider.add_span_processor(processor)
|
|
229
265
|
state.host_processors.append(processor)
|
|
230
266
|
if isinstance(host_logger_provider, LoggerProvider) and _enabled(options, LOGGING):
|
|
@@ -233,10 +269,10 @@ def enable(sdk: "StructSDK", options: Mapping[str, Mapping[str, Any]]) -> None:
|
|
|
233
269
|
)
|
|
234
270
|
host_logger_provider.add_log_record_processor(log_processor)
|
|
235
271
|
state.host_processors.append(log_processor)
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
elif not isinstance(host_logger_provider, LoggerProvider):
|
|
272
|
+
attached = len(state.host_processors) + (state.host_metric_reader is not None)
|
|
273
|
+
if attached:
|
|
274
|
+
logger.debug("Host OpenTelemetry providers present; full-app mode attached %d exporters", attached)
|
|
275
|
+
elif not isinstance(host_logger_provider, LoggerProvider) and not isinstance(host_meter_provider, MeterProvider):
|
|
240
276
|
logger.info(
|
|
241
277
|
"Struct full-app mode attached nothing: the host's OpenTelemetry providers (%s) are "
|
|
242
278
|
"not OpenTelemetry SDK providers, for example ddtrace with DD_TRACE_OTEL_ENABLED. "
|
|
@@ -246,16 +282,21 @@ def enable(sdk: "StructSDK", options: Mapping[str, Mapping[str, Any]]) -> None:
|
|
|
246
282
|
return
|
|
247
283
|
|
|
248
284
|
trace.set_tracer_provider(tracer_provider)
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
285
|
+
# Struct is the app's own pipeline here, so OpenTelemetry's records about
|
|
286
|
+
# collections (an app callback that raises) stay where the app expects them.
|
|
287
|
+
with _new_metric_reader(sdk._endpoint, headers, isolate_collection=False) as reader:
|
|
288
|
+
meter_provider = MeterProvider(
|
|
289
|
+
resource=tracer_provider.resource,
|
|
290
|
+
metric_readers=[reader],
|
|
291
|
+
# StructSDK's bounded shutdown owns exit; the provider's own atexit hook
|
|
292
|
+
# would block for its 30s default on a dead collector.
|
|
293
|
+
shutdown_on_exit=False,
|
|
294
|
+
)
|
|
256
295
|
sdk._meter_provider = meter_provider
|
|
257
296
|
metrics.set_meter_provider(meter_provider)
|
|
258
297
|
_logs.set_logger_provider(logger_provider)
|
|
298
|
+
if _enabled(options, METRICS):
|
|
299
|
+
_safe(lambda: _start_struct_metrics(state, sdk._endpoint, tracer_provider, headers), site="auto.metrics")
|
|
259
300
|
|
|
260
301
|
_instrument_libraries(tracer_provider, meter_provider, options)
|
|
261
302
|
if _enabled(options, AZURE_SDK):
|
|
@@ -268,6 +309,19 @@ def enable(sdk: "StructSDK", options: Mapping[str, Mapping[str, Any]]) -> None:
|
|
|
268
309
|
_safe(bridge, site="auto.logging")
|
|
269
310
|
|
|
270
311
|
|
|
312
|
+
def _start_struct_metrics(
|
|
313
|
+
state: FullAppState, endpoint: str, tracer_provider: TracerProvider, headers: dict[str, str]
|
|
314
|
+
) -> None:
|
|
315
|
+
"""Struct's own instruments, in either mode, on a meter provider of Struct's
|
|
316
|
+
that is never global: only Struct's reader collects them, so each
|
|
317
|
+
collection's maximum and cgroup sample cover the whole interval."""
|
|
318
|
+
state.struct_meter_provider = _metrics.struct_meter_provider(tracer_provider.resource, endpoint, headers)
|
|
319
|
+
state.runtime = _metrics.RuntimeMetrics.start(state.struct_meter_provider)
|
|
320
|
+
# Struct's own spans (its GenAI spans, and everything in owned mode) find
|
|
321
|
+
# the loops they run on.
|
|
322
|
+
tracer_provider.add_span_processor(_metrics.LoopWatchingSpanProcessor(state.runtime))
|
|
323
|
+
|
|
324
|
+
|
|
271
325
|
def _is_unset(provider: Any) -> bool:
|
|
272
326
|
# The API exposes no public "unset" check for meter and logger providers;
|
|
273
327
|
# until one is installed it hands out these proxy classes.
|
|
@@ -280,7 +334,7 @@ def _with_env_disabled(
|
|
|
280
334
|
names = {n.strip() for n in os.environ.get(OTEL_PYTHON_DISABLED_INSTRUMENTATIONS, "").split(",")}
|
|
281
335
|
names.discard("")
|
|
282
336
|
if "*" in names:
|
|
283
|
-
names = {*SUPPORTED_INSTRUMENTATIONS, AZURE_SDK, LOGGING}
|
|
337
|
+
names = {*SUPPORTED_INSTRUMENTATIONS, AZURE_SDK, LOGGING, METRICS}
|
|
284
338
|
merged: dict[str, Mapping[str, Any]] = {name: {"enabled": False} for name in names}
|
|
285
339
|
for name, library_options in options.items():
|
|
286
340
|
merged[name] = {**merged.get(name, {}), **library_options}
|
|
@@ -743,12 +797,18 @@ class _HostAttachedSpanProcessor(SpanProcessor):
|
|
|
743
797
|
chain does not isolate faults: anything raised here would reach the
|
|
744
798
|
customer's span calls."""
|
|
745
799
|
|
|
746
|
-
def __init__(
|
|
800
|
+
def __init__(
|
|
801
|
+
self, inner: SpanProcessor, budget_seconds: float, *, watch_loop: Optional[Callable[[], None]] = None
|
|
802
|
+
) -> None:
|
|
747
803
|
self._inner = inner
|
|
748
804
|
self._budget_seconds = budget_seconds
|
|
805
|
+
# Lets the event-loop delay probe find the loops the host's spans run on.
|
|
806
|
+
self._watch_loop = watch_loop
|
|
749
807
|
|
|
750
808
|
def on_start(self, span: Any, parent_context: Any = None) -> None:
|
|
751
809
|
_safe(lambda: self._inner.on_start(span, parent_context=parent_context), site="auto.host_spans.on_start")
|
|
810
|
+
if self._watch_loop is not None:
|
|
811
|
+
_safe(self._watch_loop, site="auto.host_spans.watch_loop")
|
|
752
812
|
|
|
753
813
|
def _on_ending(self, span: Any) -> None:
|
|
754
814
|
_safe(lambda: getattr(self._inner, "_on_ending", lambda _span: None)(span), site="auto.host_spans.on_ending")
|