# Lambda OTel Lite
[](https://pypi.org/project/lambda-otel-lite/)
The `lambda-otel-lite` library provides a lightweight, efficient OpenTelemetry implementation specifically designed for AWS Lambda environments. It features a custom span processor and internal extension mechanism that optimizes telemetry collection for Lambda's unique execution model.
By leveraging Lambda's execution lifecycle and providing multiple processing modes, this library enables efficient telemetry collection with minimal impact on function latency. By default, it uses the [otlp-stdout-span-exporter](https://pypi.org/project/otlp-stdout-span-exporter) to export spans to stdout for the [serverless-otlp-forwarder](https://github.com/dev7a/serverless-otlp-forwarder) project.
>[!IMPORTANT]
>This package is highly experimental and should not be used in production. Contributions are welcome.
## Table of Contents
- [Requirements](#requirements)
- [Features](#features)
- [Architecture and Modules](#architecture-and-modules)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Processing Modes](#processing-modes)
- [Async Processing Mode Architecture](#async-processing-mode-architecture)
- [Telemetry Configuration](#telemetry-configuration)
- [Custom configuration with custom resource attributes](#custom-configuration-with-custom-resource-attributes)
- [Custom configuration with custom span processors](#custom-configuration-with-custom-span-processors)
- [Custom configuration with context propagators](#custom-configuration-with-context-propagators)
- [Library specific Resource Attributes](#library-specific-resource-attributes)
- [Event Extractors](#event-extractors)
- [Automatic Attributes extraction](#automatic-attributes-extraction)
- [Built-in Extractors](#built-in-extractors)
- [Custom Extractors](#custom-extractors)
- [Environment Variables](#environment-variables)
- [Processing Configuration](#processing-configuration)
- [Resource Configuration](#resource-configuration)
- [Export Configuration](#export-configuration)
- [Logging](#logging)
- [AWS Lambda Environment](#aws-lambda-environment)
- [License](#license)
- [See Also](#see-also)
## Requirements
- Python 3.12+
- OpenTelemetry packages (automatically installed as dependencies)
- For OTLP HTTP export: Additional dependencies available via `pip install "lambda_otel_lite[otlp-http]"`
## Features
- **Flexible Processing Modes**: Support for synchronous, asynchronous, and custom export strategies
- **Automatic Resource Detection**: Automatic extraction of Lambda environment attributes
- **Lambda Extension Integration**: Built-in extension for efficient telemetry export
- **Efficient Memory Usage**: Fixed-size queue to prevent memory growth
- **AWS Event Support**: Automatic extraction of attributes from common AWS event types
- **Flexible Context Propagation**: Support for W3C Trace Context and custom propagators
## Architecture and Modules
- `telemetry`: Core initialization and configuration
- Main entry point via `init_telemetry`
- Configures global tracer and span processors
- Returns a `TelemetryCompletionHandler` for span lifecycle management
- `processor`: Lambda-optimized span processor
- Fixed-size queue implementation
- Multiple processing modes
- Coordinates with extension for async export
- `extension`: Lambda Extension implementation
- Manages extension lifecycle and registration
- Handles span export coordination
- Implements graceful shutdown
- `extractors`: Event processing
- Built-in support for API Gateway and ALB events
- Extensible interface for custom events
- W3C Trace Context propagation
- `handler`: Handler decorator
- Provides `create_traced_handler` function to create tracing decorators
- Automatically tracks cold starts using the `faas.cold_start` attribute
- Extracts and propagates context from request headers
- Manages span lifecycle with automatic status handling for HTTP responses
- Records exceptions in spans with appropriate status codes
- Properly completes telemetry processing on handler completion
## Installation
```bash
# Requires Python 3.12+
pip install lambda_otel_lite
# Optional: For OTLP HTTP export support
pip install "lambda_otel_lite[otlp-http]"
```
## Quick Start
```python
from opentelemetry import trace
from lambda_otel_lite import init_telemetry, create_traced_handler
from lambda_otel_lite.extractors import api_gateway_v2_extractor
import json
# Initialize telemetry once, outside the handler
tracer, completion_handler = init_telemetry()
# Define business logic separately
def process_user(user_id):
# Your business logic here
return {"name": "User Name", "id": user_id}
# Create traced handler with specific extractor
traced = create_traced_handler(
name="my-api-handler",
completion_handler=completion_handler,
attributes_extractor=api_gateway_v2_extractor
)
@traced
def handler(event, context):
try:
# Get current span to add custom attributes
current_span = trace.get_current_span()
current_span.set_attribute("handler.version", "1.0")
# Extract userId from event path parameters
path_parameters = event.get("pathParameters", {}) or {}
user_id = path_parameters.get("userId", "unknown")
current_span.set_attribute("user.id", user_id)
# Process business logic
user = process_user(user_id)
# Return formatted HTTP response
return {
"statusCode": 200,
"headers": {"Content-Type": "application/json"},
"body": json.dumps({"success": True, "data": user})
}
except Exception as error:
# Simple error handling (see Error Handling section for more details)
return {
"statusCode": 500,
"headers": {"Content-Type": "application/json"},
"body": json.dumps({
"success": False,
"error": "Internal server error"
})
}
```
## Processing Modes
The library supports three processing modes for span export:
1. **Sync Mode** (default):
- Direct, synchronous export in handler thread
- Recommended for:
- low-volume telemetry
- limited resources (memory, cpu)
- when latency is not critical
- Set via `LAMBDA_EXTENSION_SPAN_PROCESSOR_MODE=sync`
2. **Async Mode**:
- Export via Lambda extension using AWS Lambda Extensions API
- Spans are queued and exported after handler completion
- Uses event-based communication between handler and extension
- Registers specifically for Lambda INVOKE events
- Implements graceful shutdown with SIGTERM handling
- Error handling for:
- Event communication failures
- Export failures
- Extension registration issues
- Best for production use with high telemetry volume
- Set via `LAMBDA_EXTENSION_SPAN_PROCESSOR_MODE=async`
3. **Finalize Mode**:
- Registers extension with no events
- Maintains SIGTERM handler for graceful shutdown
- Ensures all spans are flushed during shutdown
- Compatible with BatchSpanProcessor for custom export strategies
- Best for specialized export requirements where you need full control
- Set via `LAMBDA_EXTENSION_SPAN_PROCESSOR_MODE=finalize`
### Async Processing Mode Architecture
```mermaid
sequenceDiagram
participant Lambda Runtime
participant Extension Thread
participant Handler
participant LambdaSpanProcessor
participant OTLPStdoutSpanExporter
Note over Extension Thread: Initialization
Extension Thread->>Lambda Runtime: Register extension (POST /register)
Lambda Runtime-->>Extension Thread: Extension ID
Extension Thread->>Lambda Runtime: Get next event (GET /next)
Note over Handler: Function Invocation
Handler->>LambdaSpanProcessor: Create & queue spans
Note over LambdaSpanProcessor: Spans stored in fixed-size queue
Handler->>Extension Thread: Set handler_complete_event
Note over Handler: Handler returns response
Extension Thread->>LambdaSpanProcessor: process_spans()
LambdaSpanProcessor->>OTLPStdoutSpanExporter: export() batched spans
Extension Thread->>Lambda Runtime: Get next event (GET /next)
Note over Extension Thread: On SIGTERM
Lambda Runtime->>Extension Thread: SHUTDOWN event
Extension Thread->>LambdaSpanProcessor: force_flush()
LambdaSpanProcessor->>OTLPStdoutSpanExporter: export() remaining spans
```
The async mode leverages Lambda's extension API to optimize perceived latency by deferring span export until after the response is sent to the user. The diagram above shows the core coordination between components:
1. Extension thread registers and waits for events from Runtime
2. Handler queues spans during execution via LambdaSpanProcessor
3. Handler signals completion via event before returning
4. Extension processes and exports queued spans after handler completes
5. Extension returns to waiting for next event
6. On shutdown, remaining spans are flushed and exported
## Telemetry Configuration
The library provides several ways to configure the OpenTelemetry tracing pipeline, which is a required first step to instrument your Lambda function:
### Custom configuration with custom resource attributes
```python
from opentelemetry.sdk.resources import Resource
from lambda_otel_lite import init_telemetry
# Create a custom resource with additional attributes
resource = Resource.create({
"service.version": "1.0.0",
"deployment.environment": "production",
"custom.attribute": "value"
})
# Initialize with custom resource
tracer, completion_handler = init_telemetry(resource=resource)
# Use the tracer and completion handler as usual
```
### Custom configuration with custom span processors
```python
from opentelemetry.sdk.trace import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from lambda_otel_lite import init_telemetry
# First install the optional dependency:
# pip install "lambda_otel_lite[otlp-http]"
# Create a custom processor with OTLP HTTP exporter
processor = BatchSpanProcessor(
OTLPSpanExporter(
endpoint="https://your-otlp-endpoint/v1/traces"
)
)
# Initialize with custom processor
tracer, completion_handler = init_telemetry(span_processors=[processor])
```
You can provide multiple span processors, and they will all be used to process spans. This allows you to send telemetry to multiple destinations or use different processing strategies for different types of spans.
### Custom configuration with context propagators
```python
from opentelemetry.propagate import set_global_textmap
from opentelemetry.propagators.b3 import B3Format
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
from lambda_otel_lite import init_telemetry
# Create a custom configuration with specific propagators
tracer, completion_handler = init_telemetry(
propagators=[
TraceContextTextMapPropagator(), # W3C Trace Context
B3Format(), # B3 format for Zipkin compatibility
]
)
```
By default, OpenTelemetry Python uses W3C Trace Context and W3C Baggage propagators. The `propagators` parameter allows you to customize which propagators are used for context extraction and injection. This is useful when you need to integrate with systems that use different context propagation formats.
You can provide multiple propagators, and they will be combined into a composite propagator. The order matters - propagators are applied in the order they are provided.
> **Note:** The OpenTelemetry SDK also supports configuring propagators via the `OTEL_PROPAGATORS` environment variable. If set, this environment variable takes precedence over programmatic configuration. See the [OpenTelemetry Python documentation](https://opentelemetry.io/docs/languages/python/instrumentation/) for more details.
### Library specific Resource Attributes
The library adds several resource attributes under the `lambda_otel_lite` namespace to provide configuration visibility:
- `lambda_otel_lite.extension.span_processor_mode`: Current processing mode (`sync`, `async`, or `finalize`)
- `lambda_otel_lite.lambda_span_processor.queue_size`: Maximum number of spans that can be queued
- `lambda_otel_lite.lambda_span_processor.batch_size`: Maximum batch size for span export
- `lambda_otel_lite.otlp_stdout_span_exporter.compression_level`: GZIP compression level used for span export
These attributes are automatically added to the resource and can be used to understand the telemetry configuration in your observability backend.
## Event Extractors
Event extractors are responsible for extracting span attributes and context from Lambda event and context objects. The library provides built-in extractors for common Lambda triggers.
### Automatic Attributes extraction
The library automatically sets relevant FAAS attributes based on the Lambda context and event. Both `event` and `context` parameters must be passed to `tracedHandler` to enable all automatic attributes:
- Resource Attributes (set at initialization):
- `cloud.provider`: "aws"
- `cloud.region`: from AWS_REGION
- `faas.name`: from AWS_LAMBDA_FUNCTION_NAME
- `faas.version`: from AWS_LAMBDA_FUNCTION_VERSION
- `faas.instance`: from AWS_LAMBDA_LOG_STREAM_NAME
- `faas.max_memory`: from AWS_LAMBDA_FUNCTION_MEMORY_SIZE
- `service.name`: from OTEL_SERVICE_NAME (defaults to function name)
- Additional attributes from OTEL_RESOURCE_ATTRIBUTES (URL-decoded)
- Span Attributes (set per invocation when passing context):
- `faas.cold_start`: true on first invocation
- `cloud.account.id`: extracted from context's invokedFunctionArn
- `faas.invocation_id`: from awsRequestId
- `cloud.resource_id`: from context's invokedFunctionArn
- HTTP Attributes (set for API Gateway events):
- `faas.trigger`: "http"
- `http.status_code`: from handler response
- `http.route`: from routeKey (v2) or resource (v1)
- `http.method`: from requestContext (v2) or httpMethod (v1)
- `http.target`: from path
- `http.scheme`: from protocol
The library automatically detects API Gateway v1 and v2 events and sets the appropriate HTTP attributes. For HTTP responses, the status code is automatically extracted from the handler's response and set as `http.status_code`. For 5xx responses, the span status is set to ERROR.
### Built-in Extractors
```python
from lambda_otel_lite.extractors import (
api_gateway_v1_extractor, # API Gateway REST API
api_gateway_v2_extractor, # API Gateway HTTP API
alb_extractor, # Application Load Balancer
default_extractor, # Basic Lambda attributes
)
```
Each extractor is designed to handle a specific event type and extract relevant attributes:
- `api_gateway_v1_extractor`: Extracts HTTP attributes from API Gateway REST API events
- `api_gateway_v2_extractor`: Extracts HTTP attributes from API Gateway HTTP API events
- `alb_extractor`: Extracts HTTP attributes from Application Load Balancer events
- `default_extractor`: Extracts basic Lambda attributes from any event type
```python
from lambda_otel_lite.extractors import api_gateway_v1_extractor
import json
# Initialize telemetry with default configuration
tracer, completion_handler = init_telemetry()
traced = create_traced_handler(
name="api-v1-handler",
completion_handler=completion_handler,
attributes_extractor=api_gateway_v1_extractor
)
@traced
def handler(event, context):
# Your handler code
return {
"statusCode": 200,
"body": json.dumps({"message": "Hello, world!"})
}
```
### Custom Extractors
You can create custom extractors for event types not directly supported by the library by implementing the extractor interface:
```python
from lambda_otel_lite.extractors import SpanAttributes, TriggerType
from lambda_otel_lite import create_traced_handler, init_telemetry
def custom_extractor(event, context) -> SpanAttributes:
return SpanAttributes(
trigger=TriggerType.OTHER, # Or any custom string
attributes={
'custom.attribute': 'value',
# ... other attributes
},
span_name='custom-operation', # Optional
carrier=event.get('headers') # Optional: For context propagation
)
# Initialize telemetry
tracer, completion_handler = init_telemetry()
# Create traced handler with custom extractor
traced = create_traced_handler(
name="custom-handler",
completion_handler=completion_handler,
attributes_extractor=custom_extractor
)
@traced
def handler(event, context):
# Your handler code
return {"statusCode": 200}
```
The `SpanAttributes` object returned by the extractor contains:
- `trigger`: The type of trigger (HTTP, SQS, etc.) - affects how spans are named
- `attributes`: A dictionary of attributes to add to the span
- `span_name`: Optional custom name for the span (defaults to handler name)
- `carrier`: Optional dictionary containing trace context headers for propagation
## Environment Variables
The library can be configured using the following environment variables:
### Processing Configuration
- `LAMBDA_EXTENSION_SPAN_PROCESSOR_MODE`: Controls span processing strategy
- `sync`: Direct export in handler thread (default)
- `async`: Deferred export via extension
- `finalize`: Custom export strategy
- `LAMBDA_SPAN_PROCESSOR_QUEUE_SIZE`: Maximum number of spans to queue (default: 2048)
- `LAMBDA_SPAN_PROCESSOR_BATCH_SIZE`: Maximum number of spans to export in each batch (default: 512)
### Resource Configuration
- `OTEL_SERVICE_NAME`: Override the service name (defaults to function name)
- `OTEL_RESOURCE_ATTRIBUTES`: Additional resource attributes in key=value,key2=value2 format
### Export Configuration
- `OTLP_STDOUT_SPAN_EXPORTER_COMPRESSION_LEVEL`: Gzip compression level for stdout exporter
- 0: No compression
- 1: Best speed
- 6: Good balance between size and speed (default)
- 9: Best compression
### Logging
- `AWS_LAMBDA_LOG_LEVEL` or `LOG_LEVEL`: Configure log level (debug, info, warn, error, none)
### AWS Lambda Environment
The following AWS Lambda environment variables are automatically used for resource attributes:
- `AWS_REGION`: Region where function runs
- `AWS_LAMBDA_FUNCTION_NAME`: Function name
- `AWS_LAMBDA_FUNCTION_VERSION`: Function version
- `AWS_LAMBDA_LOG_STREAM_NAME`: Log stream name
- `AWS_LAMBDA_FUNCTION_MEMORY_SIZE`: Function memory size
## License
MIT
## See Also
- [GitHub](https://github.com/dev7a/serverless-otlp-forwarder) - The main project repository for the Serverless OTLP Forwarder project
- [GitHub](https://github.com/dev7a/serverless-otlp-forwarder/tree/main/packages/node/lambda-otel-lite) | [npm](https://www.npmjs.com/package/@dev7a/lambda-otel-lite) - The Node.js version of this library
- [GitHub](https://github.com/dev7a/serverless-otlp-forwarder/tree/main/packages/rust/lambda-otel-lite) | [crates.io](https://crates.io/crates/lambda-otel-lite) - The Rust version of this library
Raw data
{
"_id": null,
"home_page": null,
"name": "lambda-otel-lite",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.12",
"maintainer_email": null,
"keywords": "aws, lambda, opentelemetry, otel, tracing",
"author": null,
"author_email": "Alessandro Bologna <alessandro.bologna@gmail.com>",
"download_url": "https://files.pythonhosted.org/packages/e3/20/9534f3aca9653ebfa86f6c75675d38681739b3fdf545642069287609f520/lambda_otel_lite-0.10.2.tar.gz",
"platform": null,
"description": "# Lambda OTel Lite\n\n[](https://pypi.org/project/lambda-otel-lite/)\n\nThe `lambda-otel-lite` library provides a lightweight, efficient OpenTelemetry implementation specifically designed for AWS Lambda environments. It features a custom span processor and internal extension mechanism that optimizes telemetry collection for Lambda's unique execution model.\n\nBy leveraging Lambda's execution lifecycle and providing multiple processing modes, this library enables efficient telemetry collection with minimal impact on function latency. By default, it uses the [otlp-stdout-span-exporter](https://pypi.org/project/otlp-stdout-span-exporter) to export spans to stdout for the [serverless-otlp-forwarder](https://github.com/dev7a/serverless-otlp-forwarder) project.\n\n>[!IMPORTANT]\n>This package is highly experimental and should not be used in production. Contributions are welcome.\n\n## Table of Contents\n\n- [Requirements](#requirements)\n- [Features](#features)\n- [Architecture and Modules](#architecture-and-modules)\n- [Installation](#installation)\n- [Quick Start](#quick-start)\n- [Processing Modes](#processing-modes)\n - [Async Processing Mode Architecture](#async-processing-mode-architecture)\n- [Telemetry Configuration](#telemetry-configuration)\n - [Custom configuration with custom resource attributes](#custom-configuration-with-custom-resource-attributes)\n - [Custom configuration with custom span processors](#custom-configuration-with-custom-span-processors)\n - [Custom configuration with context propagators](#custom-configuration-with-context-propagators)\n - [Library specific Resource Attributes](#library-specific-resource-attributes)\n- [Event Extractors](#event-extractors)\n - [Automatic Attributes extraction](#automatic-attributes-extraction)\n - [Built-in Extractors](#built-in-extractors)\n - [Custom Extractors](#custom-extractors)\n- [Environment Variables](#environment-variables)\n - [Processing Configuration](#processing-configuration)\n - [Resource Configuration](#resource-configuration)\n - [Export Configuration](#export-configuration)\n - [Logging](#logging)\n - [AWS Lambda Environment](#aws-lambda-environment)\n- [License](#license)\n- [See Also](#see-also)\n\n## Requirements\n\n- Python 3.12+\n- OpenTelemetry packages (automatically installed as dependencies)\n- For OTLP HTTP export: Additional dependencies available via `pip install \"lambda_otel_lite[otlp-http]\"`\n\n## Features\n\n- **Flexible Processing Modes**: Support for synchronous, asynchronous, and custom export strategies\n- **Automatic Resource Detection**: Automatic extraction of Lambda environment attributes\n- **Lambda Extension Integration**: Built-in extension for efficient telemetry export\n- **Efficient Memory Usage**: Fixed-size queue to prevent memory growth\n- **AWS Event Support**: Automatic extraction of attributes from common AWS event types\n- **Flexible Context Propagation**: Support for W3C Trace Context and custom propagators\n\n## Architecture and Modules\n\n- `telemetry`: Core initialization and configuration\n - Main entry point via `init_telemetry`\n - Configures global tracer and span processors\n - Returns a `TelemetryCompletionHandler` for span lifecycle management\n\n- `processor`: Lambda-optimized span processor\n - Fixed-size queue implementation\n - Multiple processing modes\n - Coordinates with extension for async export\n\n- `extension`: Lambda Extension implementation\n - Manages extension lifecycle and registration\n - Handles span export coordination\n - Implements graceful shutdown\n\n- `extractors`: Event processing\n - Built-in support for API Gateway and ALB events\n - Extensible interface for custom events\n - W3C Trace Context propagation\n\n- `handler`: Handler decorator\n - Provides `create_traced_handler` function to create tracing decorators\n - Automatically tracks cold starts using the `faas.cold_start` attribute\n - Extracts and propagates context from request headers\n - Manages span lifecycle with automatic status handling for HTTP responses\n - Records exceptions in spans with appropriate status codes\n - Properly completes telemetry processing on handler completion\n\n## Installation\n\n```bash\n# Requires Python 3.12+\npip install lambda_otel_lite\n\n# Optional: For OTLP HTTP export support\npip install \"lambda_otel_lite[otlp-http]\"\n```\n\n## Quick Start\n\n```python\nfrom opentelemetry import trace\nfrom lambda_otel_lite import init_telemetry, create_traced_handler\nfrom lambda_otel_lite.extractors import api_gateway_v2_extractor\nimport json\n\n# Initialize telemetry once, outside the handler\ntracer, completion_handler = init_telemetry()\n\n# Define business logic separately\ndef process_user(user_id):\n # Your business logic here\n return {\"name\": \"User Name\", \"id\": user_id}\n\n# Create traced handler with specific extractor\ntraced = create_traced_handler(\n name=\"my-api-handler\",\n completion_handler=completion_handler,\n attributes_extractor=api_gateway_v2_extractor\n)\n\n@traced\ndef handler(event, context):\n try:\n # Get current span to add custom attributes\n current_span = trace.get_current_span()\n current_span.set_attribute(\"handler.version\", \"1.0\")\n \n # Extract userId from event path parameters\n path_parameters = event.get(\"pathParameters\", {}) or {}\n user_id = path_parameters.get(\"userId\", \"unknown\")\n current_span.set_attribute(\"user.id\", user_id)\n \n # Process business logic\n user = process_user(user_id)\n \n # Return formatted HTTP response\n return {\n \"statusCode\": 200,\n \"headers\": {\"Content-Type\": \"application/json\"},\n \"body\": json.dumps({\"success\": True, \"data\": user})\n }\n except Exception as error:\n # Simple error handling (see Error Handling section for more details)\n return {\n \"statusCode\": 500,\n \"headers\": {\"Content-Type\": \"application/json\"},\n \"body\": json.dumps({\n \"success\": False,\n \"error\": \"Internal server error\"\n })\n }\n```\n\n## Processing Modes\n\nThe library supports three processing modes for span export:\n\n1. **Sync Mode** (default):\n - Direct, synchronous export in handler thread\n - Recommended for:\n - low-volume telemetry\n - limited resources (memory, cpu)\n - when latency is not critical\n - Set via `LAMBDA_EXTENSION_SPAN_PROCESSOR_MODE=sync`\n\n2. **Async Mode**:\n - Export via Lambda extension using AWS Lambda Extensions API\n - Spans are queued and exported after handler completion\n - Uses event-based communication between handler and extension\n - Registers specifically for Lambda INVOKE events\n - Implements graceful shutdown with SIGTERM handling\n - Error handling for:\n - Event communication failures\n - Export failures\n - Extension registration issues\n - Best for production use with high telemetry volume\n - Set via `LAMBDA_EXTENSION_SPAN_PROCESSOR_MODE=async`\n\n3. **Finalize Mode**:\n - Registers extension with no events\n - Maintains SIGTERM handler for graceful shutdown\n - Ensures all spans are flushed during shutdown\n - Compatible with BatchSpanProcessor for custom export strategies\n - Best for specialized export requirements where you need full control\n - Set via `LAMBDA_EXTENSION_SPAN_PROCESSOR_MODE=finalize`\n\n### Async Processing Mode Architecture\n\n```mermaid\nsequenceDiagram\n participant Lambda Runtime\n participant Extension Thread\n participant Handler\n participant LambdaSpanProcessor\n participant OTLPStdoutSpanExporter\n\n Note over Extension Thread: Initialization\n Extension Thread->>Lambda Runtime: Register extension (POST /register)\n Lambda Runtime-->>Extension Thread: Extension ID\n Extension Thread->>Lambda Runtime: Get next event (GET /next)\n\n Note over Handler: Function Invocation\n Handler->>LambdaSpanProcessor: Create & queue spans\n Note over LambdaSpanProcessor: Spans stored in fixed-size queue\n\n Handler->>Extension Thread: Set handler_complete_event\n Note over Handler: Handler returns response\n\n Extension Thread->>LambdaSpanProcessor: process_spans()\n LambdaSpanProcessor->>OTLPStdoutSpanExporter: export() batched spans\n Extension Thread->>Lambda Runtime: Get next event (GET /next)\n\n Note over Extension Thread: On SIGTERM\n Lambda Runtime->>Extension Thread: SHUTDOWN event\n Extension Thread->>LambdaSpanProcessor: force_flush()\n LambdaSpanProcessor->>OTLPStdoutSpanExporter: export() remaining spans\n```\n\nThe async mode leverages Lambda's extension API to optimize perceived latency by deferring span export until after the response is sent to the user. The diagram above shows the core coordination between components:\n\n1. Extension thread registers and waits for events from Runtime\n2. Handler queues spans during execution via LambdaSpanProcessor\n3. Handler signals completion via event before returning\n4. Extension processes and exports queued spans after handler completes\n5. Extension returns to waiting for next event\n6. On shutdown, remaining spans are flushed and exported\n\n## Telemetry Configuration\n\nThe library provides several ways to configure the OpenTelemetry tracing pipeline, which is a required first step to instrument your Lambda function:\n\n### Custom configuration with custom resource attributes\n\n```python\nfrom opentelemetry.sdk.resources import Resource\nfrom lambda_otel_lite import init_telemetry\n\n# Create a custom resource with additional attributes\nresource = Resource.create({\n \"service.version\": \"1.0.0\",\n \"deployment.environment\": \"production\",\n \"custom.attribute\": \"value\"\n})\n\n# Initialize with custom resource\ntracer, completion_handler = init_telemetry(resource=resource)\n\n# Use the tracer and completion handler as usual\n```\n\n### Custom configuration with custom span processors\n\n```python\nfrom opentelemetry.sdk.trace import BatchSpanProcessor\nfrom opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter\nfrom lambda_otel_lite import init_telemetry\n\n# First install the optional dependency:\n# pip install \"lambda_otel_lite[otlp-http]\"\n\n# Create a custom processor with OTLP HTTP exporter\nprocessor = BatchSpanProcessor(\n OTLPSpanExporter(\n endpoint=\"https://your-otlp-endpoint/v1/traces\"\n )\n)\n\n# Initialize with custom processor\ntracer, completion_handler = init_telemetry(span_processors=[processor])\n```\n\nYou can provide multiple span processors, and they will all be used to process spans. This allows you to send telemetry to multiple destinations or use different processing strategies for different types of spans.\n\n### Custom configuration with context propagators\n\n```python\nfrom opentelemetry.propagate import set_global_textmap\nfrom opentelemetry.propagators.b3 import B3Format\nfrom opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator\nfrom lambda_otel_lite import init_telemetry\n\n# Create a custom configuration with specific propagators\ntracer, completion_handler = init_telemetry(\n propagators=[\n TraceContextTextMapPropagator(), # W3C Trace Context\n B3Format(), # B3 format for Zipkin compatibility\n ]\n)\n```\n\nBy default, OpenTelemetry Python uses W3C Trace Context and W3C Baggage propagators. The `propagators` parameter allows you to customize which propagators are used for context extraction and injection. This is useful when you need to integrate with systems that use different context propagation formats.\n\nYou can provide multiple propagators, and they will be combined into a composite propagator. The order matters - propagators are applied in the order they are provided.\n\n> **Note:** The OpenTelemetry SDK also supports configuring propagators via the `OTEL_PROPAGATORS` environment variable. If set, this environment variable takes precedence over programmatic configuration. See the [OpenTelemetry Python documentation](https://opentelemetry.io/docs/languages/python/instrumentation/) for more details.\n\n### Library specific Resource Attributes\n\nThe library adds several resource attributes under the `lambda_otel_lite` namespace to provide configuration visibility:\n\n- `lambda_otel_lite.extension.span_processor_mode`: Current processing mode (`sync`, `async`, or `finalize`)\n- `lambda_otel_lite.lambda_span_processor.queue_size`: Maximum number of spans that can be queued\n- `lambda_otel_lite.lambda_span_processor.batch_size`: Maximum batch size for span export\n- `lambda_otel_lite.otlp_stdout_span_exporter.compression_level`: GZIP compression level used for span export\n\nThese attributes are automatically added to the resource and can be used to understand the telemetry configuration in your observability backend.\n\n## Event Extractors\n\nEvent extractors are responsible for extracting span attributes and context from Lambda event and context objects. The library provides built-in extractors for common Lambda triggers.\n\n### Automatic Attributes extraction\n\nThe library automatically sets relevant FAAS attributes based on the Lambda context and event. Both `event` and `context` parameters must be passed to `tracedHandler` to enable all automatic attributes:\n\n- Resource Attributes (set at initialization):\n - `cloud.provider`: \"aws\"\n - `cloud.region`: from AWS_REGION\n - `faas.name`: from AWS_LAMBDA_FUNCTION_NAME\n - `faas.version`: from AWS_LAMBDA_FUNCTION_VERSION\n - `faas.instance`: from AWS_LAMBDA_LOG_STREAM_NAME\n - `faas.max_memory`: from AWS_LAMBDA_FUNCTION_MEMORY_SIZE\n - `service.name`: from OTEL_SERVICE_NAME (defaults to function name)\n - Additional attributes from OTEL_RESOURCE_ATTRIBUTES (URL-decoded)\n\n- Span Attributes (set per invocation when passing context):\n - `faas.cold_start`: true on first invocation\n - `cloud.account.id`: extracted from context's invokedFunctionArn\n - `faas.invocation_id`: from awsRequestId\n - `cloud.resource_id`: from context's invokedFunctionArn\n\n- HTTP Attributes (set for API Gateway events):\n - `faas.trigger`: \"http\"\n - `http.status_code`: from handler response\n - `http.route`: from routeKey (v2) or resource (v1)\n - `http.method`: from requestContext (v2) or httpMethod (v1)\n - `http.target`: from path\n - `http.scheme`: from protocol\n\nThe library automatically detects API Gateway v1 and v2 events and sets the appropriate HTTP attributes. For HTTP responses, the status code is automatically extracted from the handler's response and set as `http.status_code`. For 5xx responses, the span status is set to ERROR.\n\n### Built-in Extractors\n\n```python\nfrom lambda_otel_lite.extractors import (\n api_gateway_v1_extractor, # API Gateway REST API\n api_gateway_v2_extractor, # API Gateway HTTP API\n alb_extractor, # Application Load Balancer\n default_extractor, # Basic Lambda attributes\n)\n```\n\nEach extractor is designed to handle a specific event type and extract relevant attributes:\n\n- `api_gateway_v1_extractor`: Extracts HTTP attributes from API Gateway REST API events\n- `api_gateway_v2_extractor`: Extracts HTTP attributes from API Gateway HTTP API events\n- `alb_extractor`: Extracts HTTP attributes from Application Load Balancer events\n- `default_extractor`: Extracts basic Lambda attributes from any event type\n\n```python\nfrom lambda_otel_lite.extractors import api_gateway_v1_extractor\nimport json\n# Initialize telemetry with default configuration\ntracer, completion_handler = init_telemetry()\n\ntraced = create_traced_handler(\n name=\"api-v1-handler\",\n completion_handler=completion_handler,\n attributes_extractor=api_gateway_v1_extractor\n)\n\n@traced\ndef handler(event, context):\n # Your handler code\n return {\n \"statusCode\": 200,\n \"body\": json.dumps({\"message\": \"Hello, world!\"})\n }\n```\n\n### Custom Extractors\n\nYou can create custom extractors for event types not directly supported by the library by implementing the extractor interface:\n\n```python\nfrom lambda_otel_lite.extractors import SpanAttributes, TriggerType\nfrom lambda_otel_lite import create_traced_handler, init_telemetry\n\ndef custom_extractor(event, context) -> SpanAttributes:\n return SpanAttributes(\n trigger=TriggerType.OTHER, # Or any custom string\n attributes={\n 'custom.attribute': 'value',\n # ... other attributes\n },\n span_name='custom-operation', # Optional\n carrier=event.get('headers') # Optional: For context propagation\n )\n\n# Initialize telemetry\ntracer, completion_handler = init_telemetry()\n\n# Create traced handler with custom extractor\ntraced = create_traced_handler(\n name=\"custom-handler\",\n completion_handler=completion_handler,\n attributes_extractor=custom_extractor\n)\n\n@traced\ndef handler(event, context):\n # Your handler code\n return {\"statusCode\": 200}\n```\n\nThe `SpanAttributes` object returned by the extractor contains:\n\n- `trigger`: The type of trigger (HTTP, SQS, etc.) - affects how spans are named\n- `attributes`: A dictionary of attributes to add to the span\n- `span_name`: Optional custom name for the span (defaults to handler name)\n- `carrier`: Optional dictionary containing trace context headers for propagation\n\n## Environment Variables\n\nThe library can be configured using the following environment variables:\n\n### Processing Configuration\n- `LAMBDA_EXTENSION_SPAN_PROCESSOR_MODE`: Controls span processing strategy\n - `sync`: Direct export in handler thread (default)\n - `async`: Deferred export via extension\n - `finalize`: Custom export strategy\n- `LAMBDA_SPAN_PROCESSOR_QUEUE_SIZE`: Maximum number of spans to queue (default: 2048)\n- `LAMBDA_SPAN_PROCESSOR_BATCH_SIZE`: Maximum number of spans to export in each batch (default: 512)\n\n### Resource Configuration\n- `OTEL_SERVICE_NAME`: Override the service name (defaults to function name)\n- `OTEL_RESOURCE_ATTRIBUTES`: Additional resource attributes in key=value,key2=value2 format\n\n### Export Configuration\n- `OTLP_STDOUT_SPAN_EXPORTER_COMPRESSION_LEVEL`: Gzip compression level for stdout exporter\n - 0: No compression\n - 1: Best speed\n - 6: Good balance between size and speed (default)\n - 9: Best compression\n\n### Logging\n- `AWS_LAMBDA_LOG_LEVEL` or `LOG_LEVEL`: Configure log level (debug, info, warn, error, none)\n\n### AWS Lambda Environment\nThe following AWS Lambda environment variables are automatically used for resource attributes:\n- `AWS_REGION`: Region where function runs\n- `AWS_LAMBDA_FUNCTION_NAME`: Function name\n- `AWS_LAMBDA_FUNCTION_VERSION`: Function version\n- `AWS_LAMBDA_LOG_STREAM_NAME`: Log stream name\n- `AWS_LAMBDA_FUNCTION_MEMORY_SIZE`: Function memory size\n\n## License\n\nMIT \n\n## See Also\n\n- [GitHub](https://github.com/dev7a/serverless-otlp-forwarder) - The main project repository for the Serverless OTLP Forwarder project\n- [GitHub](https://github.com/dev7a/serverless-otlp-forwarder/tree/main/packages/node/lambda-otel-lite) | [npm](https://www.npmjs.com/package/@dev7a/lambda-otel-lite) - The Node.js version of this library\n- [GitHub](https://github.com/dev7a/serverless-otlp-forwarder/tree/main/packages/rust/lambda-otel-lite) | [crates.io](https://crates.io/crates/lambda-otel-lite) - The Rust version of this library",
"bugtrack_url": null,
"license": "MIT",
"summary": "Lightweight OpenTelemetry instrumentation for AWS Lambda",
"version": "0.10.2",
"project_urls": {
"Homepage": "https://github.com/dev7a/serverless-otlp-forwarder",
"Repository": "https://github.com/dev7a/serverless-otlp-forwarder/tree/main/packages/python/lambda-otel-lite"
},
"split_keywords": [
"aws",
" lambda",
" opentelemetry",
" otel",
" tracing"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "7e32fdc2ef55518ace5e20c7fa6870e1fe025674d40999e62fc84637c32db30e",
"md5": "7e1701fbac5dc0798a79c7cf1c294d54",
"sha256": "e7f46aae50f08b0ff632acf054401d9de8ba42267a50bb38b1d3c8d4dad35cff"
},
"downloads": -1,
"filename": "lambda_otel_lite-0.10.2-py3-none-any.whl",
"has_sig": false,
"md5_digest": "7e1701fbac5dc0798a79c7cf1c294d54",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.12",
"size": 23887,
"upload_time": "2025-03-15T04:38:23",
"upload_time_iso_8601": "2025-03-15T04:38:23.641226Z",
"url": "https://files.pythonhosted.org/packages/7e/32/fdc2ef55518ace5e20c7fa6870e1fe025674d40999e62fc84637c32db30e/lambda_otel_lite-0.10.2-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "e3209534f3aca9653ebfa86f6c75675d38681739b3fdf545642069287609f520",
"md5": "d923d0589630f098bdc63145a49cdadd",
"sha256": "d33874ff0db3e70c00b35fc1094c3db25fc93a039a5ebd429f90469f96037c3d"
},
"downloads": -1,
"filename": "lambda_otel_lite-0.10.2.tar.gz",
"has_sig": false,
"md5_digest": "d923d0589630f098bdc63145a49cdadd",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.12",
"size": 19936,
"upload_time": "2025-03-15T04:38:24",
"upload_time_iso_8601": "2025-03-15T04:38:24.888811Z",
"url": "https://files.pythonhosted.org/packages/e3/20/9534f3aca9653ebfa86f6c75675d38681739b3fdf545642069287609f520/lambda_otel_lite-0.10.2.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-03-15 04:38:24",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "dev7a",
"github_project": "serverless-otlp-forwarder",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "lambda-otel-lite"
}