OpenTelemetry Utils
A Python library designed to simplify application instrumentation using OpenTelemetry. This library provides an abstraction layer that makes instrumentation more intuitive and less intrusive in your business logic.
Features
- Simplified OpenTelemetry configuration
- Intuitive API for distributed tracing
- Utilities for metrics and structured logging
- OpenTelemetry Collector integration
- Complete context propagation support
- Full compatibility with asynchronous applications
Installation
pip install otel-utils
Basic Usage
Initial Configuration
from otel_utils import OtelConfig, OtelConfigurator
config = OtelConfig(
service_name="my-service",
environment="production",
otlp_endpoint="http://localhost:4318", # Optional
protocol="http", # "http" or "grpc", default "grpc"
trace_sample_rate=1.0, # Sampling rate, default 1.0
metric_export_interval_ms=30000, # Metrics export interval
log_level=logging.INFO, # Logging level
enable_console_logging=True, # Enable console logging
json_logging=True, # Use JSON format for logs (default: True)
additional_resources={ # Optional additional resources
"deployment.region": "us-east-1",
"team.name": "backend"
}
)
OtelConfigurator(config)
Tracing
from otel_utils import Tracer
tracer = Tracer("my-service")
# Using the decorator (auto-handles errors and status)
@tracer.trace("my_operation")
async def my_function():
# Your code here
pass
# Using the context manager for custom spans
with tracer.create_span("my_operation") as span:
span.set_attribute("key", "value")
# Your code here
# Using start_as_current_span for context propagation
with tracer.start_as_current_span("parent_span") as span:
# Operations here will be associated with parent_span
pass
Metrics
from otel_utils import Metrics
metrics = Metrics("my-service")
# Simple counter
counter = metrics.get_counter("requests_total")
counter.add(1, {"endpoint": "/api/v1/resource"})
# Histogram for latencies using a context manager
with metrics.measure_duration("request_duration", attributes={"method": "GET"}):
# Your code here
pass
# Asynchronous metrics (Observable Gauge)
def get_system_load():
return 0.5 # Calculated value
metrics.observe_async(
name="system_load",
description="Current system load",
callback=get_system_load
)
Structured Logging
The library provides a StructuredLogger that outputs logs in JSON format (when json_logging is enabled) and automatically includes tracing context.
from otel_utils import StructuredLogger
logger = StructuredLogger("my-service", environment="production")
# Using operation_context to auto-log start/end/errors
with logger.operation_context("process_order", order_id="123", customer_type="vip"):
logger.info("Starting processing")
# If an exception is raised here, it will be logged with status="failed"
# and the error message will be included in the JSON log.
# Manual logging with extra context
logger.info("Event occurred", action="login", user="user123")
OpenTelemetry Collector Integration
This library is designed to work seamlessly with the OpenTelemetry Collector. Telemetry data is sent using the OTLP protocol, which is the OpenTelemetry standard.
Collector Configuration with HTTP
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
exporters:
# configure your exporters here
service:
pipelines:
traces:
receivers: [otlp]
exporters: [your-exporter]
Collector Configuration with gRPC
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
exporters:
# configure your exporters here
service:
pipelines:
traces:
receivers: [otlp]
exporters: [your-exporter]
Best Practices
Separation of Concerns
Keep instrumentation separate from business logic by creating domain-specific abstractions. Your business code should remain clean and focused on its primary responsibilities.
Consistent Naming
Use coherent naming conventions for spans, metrics, and logs across your services. This makes it easier to correlate and analyze telemetry data.
Relevant Context
Include useful contextual information in spans and logs, but be mindful of sensitive data. Focus on information that aids debugging and monitoring.
Appropriate Granularity
Don't instrument everything. Focus on significant operations that provide value for monitoring and debugging. Consider the overhead and noise ratio when adding instrumentation.
Development
To set up the development environment:
# Create virtualenv
python -m venv venv
source venv/bin/activate # or `venv\Scripts\activate` on Windows
# Install development dependencies
pip install -e ".[dev]"
# Run tests
pytest
Contributing
- Create a feature branch (
git checkout -b feature/new-feature) - Commit your changes (
git commit -am 'Add new feature') - Push to the branch (
git push origin feature/new-feature) - Create a Pull Request
Metadata
Release files for otel-utils 1.4.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| otel_utils-1.4.2.tar.gz | 9.6 kB | Without provenance | Details for otel_utils-1.4.2.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| otel_utils-1.4.2-py3-none-any.whl | Python 3 | none | any | Details for otel_utils-1.4.2-py3-none-any.whl |
Total release size: 19.3 kB
Release files / otel_utils-1.4.2.tar.gz
| Download URL | otel_utils-1.4.2.tar.gz |
|---|---|
| Size | 9.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
73522af90064caeebd0b6428a238658ed0f49e4dd58ea46256fc268e8e94aaf4
|
|
BLAKE2b-256 checksum How to use checksums |
1a628254d8a7ae3135d06c440be1a1ce28f60f0ecf527bd976c4ffafe2acd59c
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
poetry/2.5.1 CPython/3.11.18 Linux/7.0.0-1017-azure
|
Release files / otel_utils-1.4.2-py3-none-any.whl
| Download URL | otel_utils-1.4.2-py3-none-any.whl |
|---|---|
| Size | 9.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
7e724421fda7e5cdf0cb9d2d15beaa371557752a47910ec8beadad39ea8f9b99
|
|
BLAKE2b-256 checksum How to use checksums |
3bd3cb7aca21f10382e60a878e815cabbcb648bd97ce8f67914027c4b161fb77
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
poetry/2.5.1 CPython/3.11.18 Linux/7.0.0-1017-azure
|
Security for otel-utils 1.4.2
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.