# Send traces from Rust tracing to Axiom





Use the `tracing-axiom` crate to send spans generated by the [tokio-rs/tracing](https://github.com/tokio-rs/tracing) library to Axiom. `tracing-axiom` provides a [`tracing-subscriber` layer](https://docs.rs/tracing-subscriber/latest/tracing_subscriber/layer/index.html) that exports your spans to Axiom over the OpenTelemetry protocol (OTLP). You combine it with any other layers your app already uses.

To send events from Rust without the `tracing` library, use the Axiom Rust SDK. For more information, see [Send data from Rust app to Axiom](/guides/rust).

<Note>
  `tracing-axiom` is an open-source project and welcomes your contributions. For more information, see the [GitHub repository](https://github.com/axiomhq/tracing-axiom).
</Note>

<Prerequisites />

* Use the [Tokio](https://tokio.rs) runtime in your app. `tracing-axiom` exports spans in the background on a Tokio runtime, so create the layer inside an async context such as `#[tokio::main]`.

## Install crate [#install-crate]

Add the following to your `Cargo.toml`:

```toml
[dependencies]
tracing-axiom = "0.7"
tracing = "0.1"
tracing-subscriber = "0.3"
tokio = { version = "1", features = ["full"] }
opentelemetry = "0.22"
```

The `opentelemetry` dependency is needed to flush spans when your app exits. Use the same `opentelemetry` version as `tracing-axiom`. Version 0.7 of `tracing-axiom` depends on `opentelemetry` 0.22. If your app depends on a different `opentelemetry` version, the shutdown call in the examples below doesn’t reach the tracer provider that `tracing-axiom` installs, and the last batch of spans is lost.

## Configure environment [#configure-environment]

`tracing-axiom` reads its configuration from the following environment variables:

```sh
export AXIOM_TOKEN="API_TOKEN"
export AXIOM_DATASET="DATASET_NAME"
export AXIOM_URL="https://AXIOM_DOMAIN"
```

<Info>
  <ReplaceDatasetToken />

  <ReplaceDomain />
</Info>

`AXIOM_URL` is the base URL of the endpoint. `tracing-axiom` appends the `/v1/traces` path. If you don’t set `AXIOM_URL`, `tracing-axiom` sends traces to `https://api.axiom.co`. Recommended: Set `AXIOM_URL` to the edge deployment where your dataset lives.

The following edge domains are available:

<BaseDomains />

<Note>
  `tracing-axiom` only accepts API tokens (`xaat-`). Personal access tokens (`xapt-`) return an `InvalidToken` error when you create the layer.
</Note>

## Send traces [#send-traces]

Create the layer with `tracing_axiom::default`, add it to a `tracing-subscriber` registry, and instrument your functions:

```rust
use tracing_subscriber::{layer::SubscriberExt as _, util::SubscriberInitExt as _, Registry};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Read AXIOM_TOKEN, AXIOM_DATASET, and AXIOM_URL from the environment
    let axiom_layer = tracing_axiom::default("my-service")?;
    Registry::default().with(axiom_layer).init();

    handle_request(42);

    // Flush buffered spans before the process exits
    opentelemetry::global::shutdown_tracer_provider();
    Ok(())
}

#[tracing::instrument]
fn handle_request(user_id: u64) {
    tracing::info!("Handling request");
}
```

The argument of `tracing_axiom::default` is the service name. Axiom stores it in the `service.name` resource attribute of every span. Each function annotated with `#[tracing::instrument]` becomes a span, and the function arguments become span attributes. Events such as `tracing::info!` inside a span are recorded as span events.

`tracing-axiom` batches spans and sends them in the background. Call `opentelemetry::global::shutdown_tracer_provider` before your app exits to send the remaining spans.

## Configure layer in code [#configure-layer-in-code]

To set the configuration in code instead of environment variables, use `tracing_axiom::builder`:

```rust
use std::time::Duration;
use tracing_subscriber::{layer::SubscriberExt as _, util::SubscriberInitExt as _, Registry};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let axiom_layer = tracing_axiom::builder("my-service")
        .with_token("API_TOKEN")?
        .with_dataset("DATASET_NAME")?
        .with_url("https://AXIOM_DOMAIN")?
        // Add resource attributes to all spans
        .with_tags([("deployment.environment", "production")].into_iter())
        // Set the export timeout. The default is 3 seconds.
        .with_timeout(Duration::from_secs(10))
        .build()?;
    Registry::default().with(axiom_layer).init();

    // ...

    opentelemetry::global::shutdown_tracer_provider();
    Ok(())
}
```

<Info>
  <ReplaceDatasetToken />

  <ReplaceDomain />
</Info>

`tracing_axiom::builder` ignores the environment. To read the environment first and override individual values in code, use `tracing_axiom::builder_with_env`. Values that you set in code take precedence over environment variables.

The builder provides the following methods:

| Method              | Description                                                           |
| :------------------ | :-------------------------------------------------------------------- |
| `with_token`        | Axiom API token. Overrides `AXIOM_TOKEN`.                             |
| `with_dataset`      | Name of the dataset where you send traces. Overrides `AXIOM_DATASET`. |
| `with_url`          | Base URL of the endpoint. Overrides `AXIOM_URL`.                      |
| `with_service_name` | Value of the `service.name` resource attribute.                       |
| `with_tags`         | Resource attributes added to all spans.                               |
| `with_timeout`      | Timeout of the OTLP exporter. The default is 3 seconds.               |
| `with_trace_config` | OpenTelemetry SDK trace configuration, for example, a custom sampler. |

## Combine with other layers [#combine-with-other-layers]

`tracing_axiom::default` and `build` return a standard `tracing-subscriber` layer. To print spans and events to the console in addition to sending them to Axiom, add a `fmt` layer to the same registry:

```rust
use tracing_subscriber::{filter::LevelFilter, prelude::*};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let axiom_layer = tracing_axiom::builder_with_env("my-service")?.build()?;
    // Filter console output so that the exporter’s own debug logs stay hidden
    let fmt_layer = tracing_subscriber::fmt::layer().with_filter(LevelFilter::INFO);

    tracing_subscriber::registry()
        .with(fmt_layer)
        .with(axiom_layer)
        .try_init()?;

    handle_request(42);

    opentelemetry::global::shutdown_tracer_provider();
    Ok(())
}

#[tracing::instrument]
fn handle_request(user_id: u64) {
    tracing::info!("Handling request");
}
```

## Optional features [#optional-features]

`tracing-axiom` provides the following [Cargo features](https://doc.rust-lang.org/stable/cargo/reference/features.html#the-features-section) to choose the TLS implementation:

* `rustls-tls`: Enables TLS functionality provided by `rustls`. Enabled by default.
* `native-tls`: Enables TLS functionality provided by `native-tls`.
* `default-tls`: Enables the default TLS implementation of `reqwest`.

## Limitations [#limitations]

* `tracing-axiom` exports spans. Events emitted outside of a span aren’t sent to Axiom. To send these events, wrap them in a span or use the [Axiom Rust SDK](/guides/rust).
* The OpenTelemetry exporter requires a multi-threaded Tokio runtime. In tests, use `#[tokio::test(flavor = "multi_thread")]`. With the default single-threaded test runtime, tests that export spans can hang.
* The standard OpenTelemetry environment variables `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` and `OTEL_EXPORTER_OTLP_ENDPOINT` take precedence over `AXIOM_URL` and `with_url`. If you set them for another exporter, unset them for apps that use `tracing-axiom`.

## View traces [#view-traces]

After your app sends spans, query them in the dataset you specified. For more information, see [Explore traces](/query-data/traces).

## Reference [#reference]

* For a full reference of the crate’s API, see [docs.rs](https://docs.rs/tracing-axiom).
* For more examples, see the [examples in GitHub](https://github.com/axiomhq/tracing-axiom/tree/main/examples).
* To use the OpenTelemetry SDK directly instead of `tracing-axiom`, see [Send OpenTelemetry data to Axiom](/send-data/opentelemetry).
