Skip to main content

Utilidades simplificadas para instrumentación con OpenTelemetry

Project description

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

  1. Create a feature branch (git checkout -b feature/new-feature)
  2. Commit your changes (git commit -am 'Add new feature')
  3. Push to the branch (git push origin feature/new-feature)
  4. Create a Pull Request

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

otel_utils-1.4.0.tar.gz (9.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

otel_utils-1.4.0-py3-none-any.whl (9.5 kB view details)

Uploaded Python 3

File details

Details for the file otel_utils-1.4.0.tar.gz.

File metadata

  • Download URL: otel_utils-1.4.0.tar.gz
  • Upload date:
  • Size: 9.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.3.2 CPython/3.11.14 Linux/6.11.0-1018-azure

File hashes

Hashes for otel_utils-1.4.0.tar.gz
Algorithm Hash digest
SHA256 99c95e0b48e8be8828e22c82dfed17efbfd3c9c6afd48494fa21fe8769802685
MD5 56141e5277fe473534c49201227a431d
BLAKE2b-256 40402500b109fc280eb5c50adb7a11766b7a944d7a9b55f58b0e8688fe2d3bc2

See more details on using hashes here.

File details

Details for the file otel_utils-1.4.0-py3-none-any.whl.

File metadata

  • Download URL: otel_utils-1.4.0-py3-none-any.whl
  • Upload date:
  • Size: 9.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.3.2 CPython/3.11.14 Linux/6.11.0-1018-azure

File hashes

Hashes for otel_utils-1.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 7a6d585733e0dff2fabac8af2fee58085fc8f6798bd4f844fd0714aa1866ed66
MD5 3b4f974c9e904a21dfe583c0b411d3d7
BLAKE2b-256 e7320cc1873249dd2ac1da1928168a4805b03d3aaa243c6984bcf384e9d02ee0

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page