> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/open-telemetry/opentelemetry-rust/llms.txt
> Use this file to discover all available pages before exploring further.

# Runtime configuration

> Configure OpenTelemetry using environment variables and feature flags

## Overview

OpenTelemetry Rust can be configured through:

* Environment variables (runtime configuration)
* Cargo feature flags (compile-time configuration)
* Programmatic configuration (in code)

## Environment variables

### General configuration

| Variable                   | Description                                     | Default           |
| -------------------------- | ----------------------------------------------- | ----------------- |
| `OTEL_SDK_DISABLED`        | Disable the SDK                                 | `false`           |
| `OTEL_RESOURCE_ATTRIBUTES` | Resource attributes as key-value pairs          |                   |
| `OTEL_SERVICE_NAME`        | Service name                                    | `unknown_service` |
| `OTEL_LOG_LEVEL`           | SDK log level (error, warn, info, debug, trace) | `info`            |

### OTLP exporter configuration

| Variable                         | Description                               | Default                 |
| -------------------------------- | ----------------------------------------- | ----------------------- |
| `OTEL_EXPORTER_OTLP_ENDPOINT`    | OTLP endpoint URL                         | `http://localhost:4317` |
| `OTEL_EXPORTER_OTLP_PROTOCOL`    | Protocol (grpc, http/protobuf, http/json) | `grpc`                  |
| `OTEL_EXPORTER_OTLP_TIMEOUT`     | Export timeout in milliseconds            | `10000`                 |
| `OTEL_EXPORTER_OTLP_HEADERS`     | Headers as key-value pairs                |                         |
| `OTEL_EXPORTER_OTLP_COMPRESSION` | Compression (gzip, none)                  | `none`                  |

### Signal-specific endpoints

| Variable                              | Description      |
| ------------------------------------- | ---------------- |
| `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`  | Traces endpoint  |
| `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` | Metrics endpoint |
| `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT`    | Logs endpoint    |
| `OTEL_EXPORTER_OTLP_TRACES_HEADERS`   | Traces headers   |
| `OTEL_EXPORTER_OTLP_METRICS_HEADERS`  | Metrics headers  |
| `OTEL_EXPORTER_OTLP_LOGS_HEADERS`     | Logs headers     |

### Batch processor configuration

**Spans:**

| Variable                         | Description          | Default |
| -------------------------------- | -------------------- | ------- |
| `OTEL_BSP_MAX_QUEUE_SIZE`        | Max queue size       | `2048`  |
| `OTEL_BSP_MAX_EXPORT_BATCH_SIZE` | Max batch size       | `512`   |
| `OTEL_BSP_SCHEDULE_DELAY`        | Export interval (ms) | `5000`  |
| `OTEL_BSP_EXPORT_TIMEOUT`        | Export timeout (ms)  | `30000` |

**Logs:**

| Variable                          | Description          | Default |
| --------------------------------- | -------------------- | ------- |
| `OTEL_BLRP_MAX_QUEUE_SIZE`        | Max queue size       | `2048`  |
| `OTEL_BLRP_MAX_EXPORT_BATCH_SIZE` | Max batch size       | `512`   |
| `OTEL_BLRP_SCHEDULE_DELAY`        | Export interval (ms) | `1000`  |
| `OTEL_BLRP_EXPORT_TIMEOUT`        | Export timeout (ms)  | `30000` |

### Trace configuration

| Variable                            | Description                | Default                 |
| ----------------------------------- | -------------------------- | ----------------------- |
| `OTEL_TRACES_SAMPLER`               | Sampler type               | `parentbased_always_on` |
| `OTEL_TRACES_SAMPLER_ARG`           | Sampler argument           |                         |
| `OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT`   | Max attributes per span    | `128`                   |
| `OTEL_SPAN_EVENT_COUNT_LIMIT`       | Max events per span        | `128`                   |
| `OTEL_SPAN_LINK_COUNT_LIMIT`        | Max links per span         | `128`                   |
| `OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT` | Max attribute value length | unlimited               |

### Sampler types

* `always_on` - Sample all spans
* `always_off` - Sample no spans
* `traceidratio` - Sample based on trace ID (requires `OTEL_TRACES_SAMPLER_ARG` = ratio)
* `parentbased_always_on` - Use parent decision, otherwise always sample
* `parentbased_always_off` - Use parent decision, otherwise never sample
* `parentbased_traceidratio` - Use parent decision, otherwise ratio-based

### Propagator configuration

| Variable           | Description                         | Default                |
| ------------------ | ----------------------------------- | ---------------------- |
| `OTEL_PROPAGATORS` | Comma-separated list of propagators | `tracecontext,baggage` |

Supported propagators:

* `tracecontext` - W3C Trace Context
* `baggage` - W3C Baggage
* `b3` - B3 single header
* `b3multi` - B3 multi header
* `jaeger` - Jaeger propagation
* `xray` - AWS X-Ray
* `ottrace` - OpenTracing

## Feature flags

### opentelemetry crate

```toml theme={null}
[dependencies]
opentelemetry = { version = "0.31", features = [
    "trace",           # Tracing API
    "metrics",         # Metrics API
    "logs",            # Logs API
    "internal-logs",   # Internal SDK logging
]}
```

### opentelemetry-sdk crate

```toml theme={null}
[dependencies]
opentelemetry_sdk = { version = "0.31", features = [
    "trace",           # Tracing SDK
    "metrics",         # Metrics SDK
    "logs",            # Logs SDK
    "rt-tokio",        # Tokio runtime for batch processors
    "rt-tokio-current-thread",  # Tokio current-thread runtime
]}
```

**Experimental features:**

```toml theme={null}
[dependencies]
opentelemetry_sdk = { version = "0.31", features = [
    "jaeger_remote_sampler",  # Jaeger remote sampling
    "experimental_metrics_periodicreader_with_async_runtime",
    "experimental_logs_batch_log_processor_with_async_runtime",
    "experimental_trace_batch_span_processor_with_async_runtime",
]}
```

### opentelemetry-otlp crate

```toml theme={null}
[dependencies]
opentelemetry-otlp = { version = "0.31", features = [
    "grpc-tonic",      # gRPC with tonic
    "http-proto",      # HTTP with protobuf
    "http-json",       # HTTP with JSON
    "reqwest-blocking", # Blocking reqwest client
    "reqwest-rustls",  # Reqwest with rustls
    "compression-gzip", # gzip compression
    "compression-zstd", # zstd compression
]}
```

## Complete configuration example

### Environment file (.env)

```bash theme={null}
# Service identification
OTEL_SERVICE_NAME=my-rust-service
OTEL_RESOURCE_ATTRIBUTES=service.version=1.0.0,deployment.environment=production

# OTLP exporter
OTEL_EXPORTER_OTLP_ENDPOINT=https://otel-collector.example.com:4317
OTEL_EXPORTER_OTLP_PROTOCOL=grpc
OTEL_EXPORTER_OTLP_HEADERS=api-key=secret123
OTEL_EXPORTER_OTLP_COMPRESSION=gzip
OTEL_EXPORTER_OTLP_TIMEOUT=30000

# Batch processing
OTEL_BSP_MAX_QUEUE_SIZE=4096
OTEL_BSP_MAX_EXPORT_BATCH_SIZE=1024
OTEL_BSP_SCHEDULE_DELAY=10000

# Sampling
OTEL_TRACES_SAMPLER=parentbased_traceidratio
OTEL_TRACES_SAMPLER_ARG=0.1

# Propagation
OTEL_PROPAGATORS=tracecontext,baggage

# Limits
OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT=256
OTEL_SPAN_EVENT_COUNT_LIMIT=256
```

### Cargo.toml

```toml theme={null}
[dependencies]
opentelemetry = { version = "0.31", features = ["trace", "metrics", "logs"] }
opentelemetry_sdk = { version = "0.31", features = ["trace", "metrics", "logs", "rt-tokio"] }
opentelemetry-otlp = { version = "0.31", features = [
    "grpc-tonic",
    "compression-gzip",
    "reqwest-rustls",
]}
```

### Application code

```rust theme={null}
use opentelemetry::global;
use opentelemetry_sdk::{
    trace::{TracerProvider, BatchSpanProcessor},
    Resource,
    runtime::Tokio,
};
use opentelemetry_otlp::SpanExporter;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Resource detection uses OTEL_SERVICE_NAME and OTEL_RESOURCE_ATTRIBUTES
    let resource = Resource::builder().build();
    
    // Exporter uses OTEL_EXPORTER_OTLP_* variables
    let exporter = SpanExporter::builder()
        .with_tonic()  // Uses OTEL_EXPORTER_OTLP_ENDPOINT
        .build()?;
    
    // Batch processor uses OTEL_BSP_* variables
    let processor = BatchSpanProcessor::builder(exporter, Tokio).build();
    
    let provider = TracerProvider::builder()
        .with_resource(resource)
        .with_span_processor(processor)
        .build();
    
    global::set_tracer_provider(provider);
    
    // Application code...
    
    global::shutdown_tracer_provider();
    Ok(())
}
```

## Override precedence

Configuration is resolved in this order (highest to lowest priority):

1. **Programmatic configuration** - Values set in code
2. **Environment variables** - Runtime configuration
3. **Default values** - Built-in defaults

```rust theme={null}
// Programmatic configuration takes precedence
let exporter = SpanExporter::builder()
    .with_tonic()
    .with_endpoint("http://custom-endpoint:4317")  // Overrides OTEL_EXPORTER_OTLP_ENDPOINT
    .build()?;
```

## Best practices

<Tip>
  **Use environment variables for deployment** - Different environments (dev, staging, prod) can have different configurations without code changes.
</Tip>

<Note>
  **Validate configuration** - Check that environment variables are set correctly before running in production.
</Note>

<Warning>
  **Secure sensitive values** - Don't commit API keys or tokens to version control. Use secret management systems.
</Warning>

<Info>
  **Feature flags reduce binary size** - Only enable the features you need to minimize dependencies and compile time.
</Info>

## Configuration by environment

### Development

```bash theme={null}
OTEL_SERVICE_NAME=my-service-dev
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317
OTEL_TRACES_SAMPLER=always_on
OTEL_BSP_SCHEDULE_DELAY=1000  # Fast export for debugging
```

### Staging

```bash theme={null}
OTEL_SERVICE_NAME=my-service-staging
OTEL_EXPORTER_OTLP_ENDPOINT=https://staging-collector.example.com:4317
OTEL_TRACES_SAMPLER=parentbased_traceidratio
OTEL_TRACES_SAMPLER_ARG=0.5  # 50% sampling
OTEL_RESOURCE_ATTRIBUTES=deployment.environment=staging
```

### Production

```bash theme={null}
OTEL_SERVICE_NAME=my-service
OTEL_EXPORTER_OTLP_ENDPOINT=https://collector.example.com:4317
OTEL_EXPORTER_OTLP_HEADERS=api-key=${SECRET_API_KEY}
OTEL_TRACES_SAMPLER=parentbased_traceidratio
OTEL_TRACES_SAMPLER_ARG=0.1  # 10% sampling
OTEL_RESOURCE_ATTRIBUTES=deployment.environment=production,service.version=${APP_VERSION}
OTEL_BSP_MAX_QUEUE_SIZE=8192  # Higher throughput
```

## Related

<CardGroup cols={2}>
  <Card title="Resource detection" icon="microchip" href="/advanced/resource-detection">
    Configure resource attributes
  </Card>

  <Card title="Batch processing" icon="layer-group" href="/advanced/batch-processing">
    Tune batch processor settings
  </Card>
</CardGroup>
