Skip to content

strands.telemetry.config

OpenTelemetry configuration and setup utilities for Strands agents.

This module provides centralized configuration and initialization functionality for OpenTelemetry components and other telemetry infrastructure shared across Strands applications.

logger = logging.getLogger(__name__) module-attribute

StrandsTelemetry

OpenTelemetry configuration and setup for Strands applications.

Automatically initializes a tracer provider with text map propagators. Trace exporters (console, OTLP) can be set up individually using dedicated methods that support method chaining for convenient configuration.

Parameters:

Name Type Description Default
tracer_provider TracerProvider | None

Optional pre-configured SDKTracerProvider. If None, a new one will be created and set as the global tracer provider.

None
Environment Variables

Environment variables are handled by the underlying OpenTelemetry SDK: - OTEL_EXPORTER_OTLP_ENDPOINT: OTLP endpoint URL - OTEL_EXPORTER_OTLP_HEADERS: Headers for OTLP requests

Examples:

Quick setup with method chaining:

>>> StrandsTelemetry().setup_console_exporter().setup_otlp_exporter()

Using a custom tracer provider:

>>> StrandsTelemetry(tracer_provider=my_provider).setup_console_exporter()

Step-by-step configuration:

>>> telemetry = StrandsTelemetry()
>>> telemetry.setup_console_exporter()
>>> telemetry.setup_otlp_exporter()

To setup global meter provider

>>> telemetry.setup_meter(enable_console_exporter=True, enable_otlp_exporter=True) # default are False
Note
  • The tracer provider is automatically initialized upon instantiation
  • When no tracer_provider is provided, the instance sets itself as the global provider
  • Exporters must be explicitly configured using the setup methods
  • Failed exporter configurations are logged but do not raise exceptions
  • All setup methods return self to enable method chaining
Source code in strands/telemetry/config.py
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
class StrandsTelemetry:
    """OpenTelemetry configuration and setup for Strands applications.

    Automatically initializes a tracer provider with text map propagators.
    Trace exporters (console, OTLP) can be set up individually using dedicated methods
    that support method chaining for convenient configuration.

    Args:
        tracer_provider: Optional pre-configured SDKTracerProvider. If None,
            a new one will be created and set as the global tracer provider.

    Environment Variables:
        Environment variables are handled by the underlying OpenTelemetry SDK:
        - OTEL_EXPORTER_OTLP_ENDPOINT: OTLP endpoint URL
        - OTEL_EXPORTER_OTLP_HEADERS: Headers for OTLP requests

    Examples:
        Quick setup with method chaining:
        >>> StrandsTelemetry().setup_console_exporter().setup_otlp_exporter()

        Using a custom tracer provider:
        >>> StrandsTelemetry(tracer_provider=my_provider).setup_console_exporter()

        Step-by-step configuration:
        >>> telemetry = StrandsTelemetry()
        >>> telemetry.setup_console_exporter()
        >>> telemetry.setup_otlp_exporter()

        To setup global meter provider
        >>> telemetry.setup_meter(enable_console_exporter=True, enable_otlp_exporter=True) # default are False

    Note:
        - The tracer provider is automatically initialized upon instantiation
        - When no tracer_provider is provided, the instance sets itself as the global provider
        - Exporters must be explicitly configured using the setup methods
        - Failed exporter configurations are logged but do not raise exceptions
        - All setup methods return self to enable method chaining
    """

    def __init__(
        self,
        tracer_provider: SDKTracerProvider | None = None,
    ) -> None:
        """Initialize the StrandsTelemetry instance.

        Args:
            tracer_provider: Optional pre-configured tracer provider.
                If None, a new one will be created and set as global.

        The instance is ready to use immediately after initialization, though
        trace exporters must be configured separately using the setup methods.
        """
        self.resource = get_otel_resource()
        if tracer_provider:
            self.tracer_provider = tracer_provider
        else:
            self._initialize_tracer()

    def _initialize_tracer(self) -> None:
        """Initialize the OpenTelemetry tracer."""
        logger.info("Initializing tracer")

        # Create tracer provider
        self.tracer_provider = SDKTracerProvider(resource=self.resource)

        # Set as global tracer provider
        trace_api.set_tracer_provider(self.tracer_provider)

        # Set up propagators
        propagate.set_global_textmap(
            CompositePropagator(
                [
                    W3CBaggagePropagator(),
                    TraceContextTextMapPropagator(),
                ]
            )
        )

    def setup_console_exporter(self, **kwargs: Any) -> "StrandsTelemetry":
        """Set up console exporter for the tracer provider.

        Args:
            **kwargs: Optional keyword arguments passed directly to
                OpenTelemetry's ConsoleSpanExporter initializer.

        Returns:
            self: Enables method chaining.

        This method configures a SimpleSpanProcessor with a ConsoleSpanExporter,
        allowing trace data to be output to the console. Any additional keyword
        arguments provided will be forwarded to the ConsoleSpanExporter.
        """
        try:
            logger.info("Enabling console export")
            console_processor = SimpleSpanProcessor(ConsoleSpanExporter(**kwargs))
            self.tracer_provider.add_span_processor(console_processor)
        except Exception as e:
            logger.exception("error=<%s> | Failed to configure console exporter", e)
        return self

    def setup_otlp_exporter(self, **kwargs: Any) -> "StrandsTelemetry":
        """Set up OTLP exporter for the tracer provider.

        Args:
            **kwargs: Optional keyword arguments passed directly to
                OpenTelemetry's OTLPSpanExporter initializer.

        Returns:
            self: Enables method chaining.

        This method configures a BatchSpanProcessor with an OTLPSpanExporter,
        allowing trace data to be exported to an OTLP endpoint. Any additional
        keyword arguments provided will be forwarded to the OTLPSpanExporter.
        """
        from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter

        try:
            otlp_exporter = OTLPSpanExporter(**kwargs)
            batch_processor = BatchSpanProcessor(otlp_exporter)
            self.tracer_provider.add_span_processor(batch_processor)
            logger.info("OTLP exporter configured")
        except Exception as e:
            logger.exception("error=<%s> | Failed to configure OTLP exporter", e)
        return self

    def setup_meter(
        self, enable_console_exporter: bool = False, enable_otlp_exporter: bool = False
    ) -> "StrandsTelemetry":
        """Initialize the OpenTelemetry Meter."""
        logger.info("Initializing meter")
        metrics_readers = []
        try:
            if enable_console_exporter:
                logger.info("Enabling console metrics exporter")
                console_reader = PeriodicExportingMetricReader(ConsoleMetricExporter())
                metrics_readers.append(console_reader)
            if enable_otlp_exporter:
                logger.info("Enabling OTLP metrics exporter")
                from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter

                otlp_reader = PeriodicExportingMetricReader(OTLPMetricExporter())
                metrics_readers.append(otlp_reader)
        except Exception as e:
            logger.exception("error=<%s> | Failed to configure OTLP metrics exporter", e)

        self.meter_provider = metrics_sdk.MeterProvider(resource=self.resource, metric_readers=metrics_readers)

        # Set as global tracer provider
        metrics_api.set_meter_provider(self.meter_provider)
        logger.info("Strands Meter configured")
        return self

__init__(tracer_provider=None)

Initialize the StrandsTelemetry instance.

Parameters:

Name Type Description Default
tracer_provider TracerProvider | None

Optional pre-configured tracer provider. If None, a new one will be created and set as global.

None

The instance is ready to use immediately after initialization, though trace exporters must be configured separately using the setup methods.

Source code in strands/telemetry/config.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def __init__(
    self,
    tracer_provider: SDKTracerProvider | None = None,
) -> None:
    """Initialize the StrandsTelemetry instance.

    Args:
        tracer_provider: Optional pre-configured tracer provider.
            If None, a new one will be created and set as global.

    The instance is ready to use immediately after initialization, though
    trace exporters must be configured separately using the setup methods.
    """
    self.resource = get_otel_resource()
    if tracer_provider:
        self.tracer_provider = tracer_provider
    else:
        self._initialize_tracer()

setup_console_exporter(**kwargs)

Set up console exporter for the tracer provider.

Parameters:

Name Type Description Default
**kwargs Any

Optional keyword arguments passed directly to OpenTelemetry's ConsoleSpanExporter initializer.

{}

Returns:

Name Type Description
self StrandsTelemetry

Enables method chaining.

This method configures a SimpleSpanProcessor with a ConsoleSpanExporter, allowing trace data to be output to the console. Any additional keyword arguments provided will be forwarded to the ConsoleSpanExporter.

Source code in strands/telemetry/config.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def setup_console_exporter(self, **kwargs: Any) -> "StrandsTelemetry":
    """Set up console exporter for the tracer provider.

    Args:
        **kwargs: Optional keyword arguments passed directly to
            OpenTelemetry's ConsoleSpanExporter initializer.

    Returns:
        self: Enables method chaining.

    This method configures a SimpleSpanProcessor with a ConsoleSpanExporter,
    allowing trace data to be output to the console. Any additional keyword
    arguments provided will be forwarded to the ConsoleSpanExporter.
    """
    try:
        logger.info("Enabling console export")
        console_processor = SimpleSpanProcessor(ConsoleSpanExporter(**kwargs))
        self.tracer_provider.add_span_processor(console_processor)
    except Exception as e:
        logger.exception("error=<%s> | Failed to configure console exporter", e)
    return self

setup_meter(enable_console_exporter=False, enable_otlp_exporter=False)

Initialize the OpenTelemetry Meter.

Source code in strands/telemetry/config.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
def setup_meter(
    self, enable_console_exporter: bool = False, enable_otlp_exporter: bool = False
) -> "StrandsTelemetry":
    """Initialize the OpenTelemetry Meter."""
    logger.info("Initializing meter")
    metrics_readers = []
    try:
        if enable_console_exporter:
            logger.info("Enabling console metrics exporter")
            console_reader = PeriodicExportingMetricReader(ConsoleMetricExporter())
            metrics_readers.append(console_reader)
        if enable_otlp_exporter:
            logger.info("Enabling OTLP metrics exporter")
            from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter

            otlp_reader = PeriodicExportingMetricReader(OTLPMetricExporter())
            metrics_readers.append(otlp_reader)
    except Exception as e:
        logger.exception("error=<%s> | Failed to configure OTLP metrics exporter", e)

    self.meter_provider = metrics_sdk.MeterProvider(resource=self.resource, metric_readers=metrics_readers)

    # Set as global tracer provider
    metrics_api.set_meter_provider(self.meter_provider)
    logger.info("Strands Meter configured")
    return self

setup_otlp_exporter(**kwargs)

Set up OTLP exporter for the tracer provider.

Parameters:

Name Type Description Default
**kwargs Any

Optional keyword arguments passed directly to OpenTelemetry's OTLPSpanExporter initializer.

{}

Returns:

Name Type Description
self StrandsTelemetry

Enables method chaining.

This method configures a BatchSpanProcessor with an OTLPSpanExporter, allowing trace data to be exported to an OTLP endpoint. Any additional keyword arguments provided will be forwarded to the OTLPSpanExporter.

Source code in strands/telemetry/config.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
def setup_otlp_exporter(self, **kwargs: Any) -> "StrandsTelemetry":
    """Set up OTLP exporter for the tracer provider.

    Args:
        **kwargs: Optional keyword arguments passed directly to
            OpenTelemetry's OTLPSpanExporter initializer.

    Returns:
        self: Enables method chaining.

    This method configures a BatchSpanProcessor with an OTLPSpanExporter,
    allowing trace data to be exported to an OTLP endpoint. Any additional
    keyword arguments provided will be forwarded to the OTLPSpanExporter.
    """
    from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter

    try:
        otlp_exporter = OTLPSpanExporter(**kwargs)
        batch_processor = BatchSpanProcessor(otlp_exporter)
        self.tracer_provider.add_span_processor(batch_processor)
        logger.info("OTLP exporter configured")
    except Exception as e:
        logger.exception("error=<%s> | Failed to configure OTLP exporter", e)
    return self

get_otel_resource()

Create a standard OpenTelemetry resource with service information.

Returns:

Type Description
Resource

Resource object with standard service information.

Source code in strands/telemetry/config.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
def get_otel_resource() -> Resource:
    """Create a standard OpenTelemetry resource with service information.

    Returns:
        Resource object with standard service information.
    """
    resource = Resource.create(
        {
            "service.name": "strands-agents",
            "service.version": version("strands-agents"),
            "telemetry.sdk.name": "opentelemetry",
            "telemetry.sdk.language": "python",
        }
    )

    return resource