Skip to content

iamnivekx/tracing-otel-extra

Repository files navigation

tracing-otel-extra

Crates.io Documentation License

A comprehensive collection of tracing and logging utilities for Rust applications, with special focus on Axum web framework integration and OpenTelemetry observability.

πŸš€ Features

  • Easy OpenTelemetry Integration - Simple configuration and initialization for tracing and metrics
  • Axum Web Framework Support - Structured logging middleware with request tracing
  • Multiple Output Formats - Support for Compact, Pretty, and JSON log formats
  • Distributed Tracing - Full support for OpenTelemetry distributed tracing
  • Metrics Collection - Built-in metrics collection and export capabilities
  • Automatic Resource Management - RAII pattern for automatic cleanup
  • Environment Configuration - Support for standard OpenTelemetry environment variables
  • Microservices Ready - Complete observability solution for microservices architectures

πŸ“¦ Crates

This workspace contains several specialized crates:

OpenTelemetry tracing middleware for Axum web framework

  • Structured logging middleware
  • Request/response tracing
  • Customizable span attributes
  • Metrics collection

OpenTelemetry tracing support for tracing-subscriber

  • Easy-to-use configuration through Builder pattern
  • Multiple log output formats (Compact, Pretty, JSON)
  • Automatic resource cleanup with RAII pattern
  • Built-in metrics support
  • Environment detection and configuration

Enhanced OpenTelemetry integration utilities

  • Clean, easy-to-use API for OpenTelemetry setup
  • Configurable sampling and resource attributes
  • Automatic cleanup with guard pattern
  • Support for both tracing and metrics

πŸ› οΈ Installation

Add the desired crate to your Cargo.toml:

# For Axum web framework integration
[dependencies]
axum-otel = "0.30"
axum = { version = "0.8", features = ["macros"] }
tower-http = { version = "0.6.6", features = ["trace"] }

# For general OpenTelemetry tracing
tracing-otel-extra = "0.30"
tracing = "0.1"
tokio = { version = "1.0", features = ["full"] }

πŸš€ Quick Start

Basic Axum Integration

use axum::{routing::get, Router};
use axum_otel::{AxumOtelSpanCreator, AxumOtelOnResponse, AxumOtelOnFailure};
use tower_http::trace::TraceLayer;
use tracing::Level;

async fn handler() -> &'static str {
    "Hello, World!"
}

#[tokio::main]
async fn main() {
    // Initialize tracing
    let _guard = tracing_otel_extra::Logger::new("my-service")
        .with_format(tracing_otel_extra::LogFormat::Json)
        .init()
        .expect("Failed to initialize tracing");

    // Build Axum application with tracing
    let app = Router::new()
        .route("/", get(handler))
        .layer(
            TraceLayer::new_for_http()
                .make_span_with(AxumOtelSpanCreator::new().level(Level::INFO))
                .on_response(AxumOtelOnResponse::new().level(Level::INFO))
                .on_failure(AxumOtelOnFailure::new()),
        );

    // Start server
    let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 3000));
    tracing::info!("Server listening on {}", addr);
    axum::Server::bind(&addr)
        .serve(app.into_make_service())
        .await
        .unwrap();
}

Advanced Configuration

use tracing_otel_extra::{Logger, LogFormat};
use opentelemetry::KeyValue;
use tracing::Level;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let _guard = Logger::new("production-service")
        .with_format(LogFormat::Json)
        .with_level(Level::DEBUG)
        .with_sample_ratio(0.1)  // 10% sampling
        .with_metrics_interval(60)
        .with_attributes(vec![
            KeyValue::new("environment", "production"),
            KeyValue::new("version", "1.2.3"),
        ])
        .init()?;

    tracing::info!(
        user_id = 12345,
        action = "login",
        "User logged in successfully"
    );

    Ok(())
}

πŸ“š Examples

Basic OpenTelemetry tracing setup with Jaeger visualization.

Prerequisites:

# Start Jaeger
docker run -d -p6831:6831/udp -p6832:6832/udp -p16686:16686 -p4317:4317 \
  jaegertracing/all-in-one:latest

Run:

cargo run --example otel
curl http://localhost:8080/hello

Complete microservices observability with distributed tracing using Docker Compose.

Services:

  • users-service (port 8081) - User management
  • articles-service (port 8082) - Article management
  • axum-otel-demo (port 8080) - Demo application

Observability:

  • Log Collection: Grafana Alloy β†’ Loki
  • Tracing: OpenTelemetry β†’ Tempo
  • Visualization: Grafana (Loki + Tempo)

Quick Start:

# Start all services
docker compose up -d

# Test API
curl -X POST http://localhost:8081/users \
  -H "Content-Type: application/json" \
  -d '{"name": "John Doe", "email": "[email protected]"}'

Visualization:

  • Grafana UI: loki + tempo
  • Jaeger UI: jaeger (alternative)

πŸ”§ Configuration

Environment Variables

# OTLP export configuration
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317
export OTEL_EXPORTER_OTLP_PROTOCOL=grpc

# Log level (overrides code configuration)
export RUST_LOG=debug

# Resource attributes
export OTEL_RESOURCE_ATTRIBUTES='service.name=my-service,service.version=1.0.0'

Sampling Configuration

// Sample 50% of traces
let _guard = Logger::new("service")
    .with_sample_ratio(0.5)
    .init()?;

πŸ—οΈ Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Axum App      β”‚    β”‚   tracing-otel   β”‚    β”‚  OpenTelemetry  β”‚
β”‚                 β”‚    β”‚                  β”‚    β”‚                 β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚    β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚    β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚axum-otel    β”‚ │◄──►│ β”‚Logger        β”‚ │◄──►│ β”‚Jaeger       β”‚ β”‚
β”‚ β”‚middleware   β”‚ β”‚    β”‚ β”‚Configuration β”‚ β”‚    β”‚ β”‚OTEL Collectorβ”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚    β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚    β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ“– API Reference

axum-otel

  • AxumOtelSpanCreator - Creates spans for HTTP requests
  • AxumOtelOnResponse - Handles response logging
  • AxumOtelOnFailure - Handles error logging

tracing-otel-extra

  • Logger - Main configuration builder
  • LogFormat - Log output format options
  • ProviderGuard - RAII resource management

tracing-opentelemetry-extra

  • init_tracer_provider - Initialize OpenTelemetry tracer
  • init_meter_provider - Initialize OpenTelemetry meter
  • OtelGuard - Automatic resource cleanup

🀝 Contributing

We welcome contributions! Please see our contributing guidelines:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Development Setup

# Clone the repository
git clone https://github.com/iamnivekx/tracing-otel-extra.git
cd tracing-otel-extra

# Run tests
cargo test

# Run examples
cargo run --example otel

πŸ“„ License

This project is licensed under either of

at your option.

πŸ”— Links

About

No description, website, or topics provided.

Resources

License

Apache-2.0, MIT licenses found

Licenses found

Apache-2.0
LICENSE-APACHE
MIT
LICENSE-MIT

Stars

Watchers

Forks

Packages

 
 
 

Contributors 2

  •  
  •