A comprehensive collection of tracing and logging utilities for Rust applications, with special focus on Axum web framework integration and OpenTelemetry observability.
- 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
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
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"] }
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();
}
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(())
}
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:
# 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'
// Sample 50% of traces
let _guard = Logger::new("service")
.with_sample_ratio(0.5)
.init()?;
βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββ
β Axum App β β tracing-otel β β OpenTelemetry β
β β β β β β
β βββββββββββββββ β β ββββββββββββββββ β β βββββββββββββββ β
β βaxum-otel β βββββΊβ βLogger β βββββΊβ βJaeger β β
β βmiddleware β β β βConfiguration β β β βOTEL Collectorβ β
β βββββββββββββββ β β ββββββββββββββββ β β βββββββββββββββ β
βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββ
AxumOtelSpanCreator
- Creates spans for HTTP requestsAxumOtelOnResponse
- Handles response loggingAxumOtelOnFailure
- Handles error logging
Logger
- Main configuration builderLogFormat
- Log output format optionsProviderGuard
- RAII resource management
init_tracer_provider
- Initialize OpenTelemetry tracerinit_meter_provider
- Initialize OpenTelemetry meterOtelGuard
- Automatic resource cleanup
We welcome contributions! Please see our contributing guidelines:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
# 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
This project is licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.