Skip to content

Commit

Permalink
feat: Add OpenTelemetry setup function
Browse files Browse the repository at this point in the history
  • Loading branch information
mzaniolo committed Jan 14, 2025
1 parent 77b970a commit 5f81383
Show file tree
Hide file tree
Showing 6 changed files with 596 additions and 0 deletions.
35 changes: 35 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,47 @@ time = { version = "0.3.36", optional = true }
tracing = "0.1.40"
url = { version = "2.5.2", features = ["serde"] }

# telemetry deps
async-trait = { version = "^0.1.51", optional = true }
http = { version = "1.2.0", optional = true }
once_cell = { version = "1.20.2", optional = true }
opentelemetry = { version = "0.27.1", optional = true }
opentelemetry-appender-tracing = { version = "0.27.0", optional = true }
opentelemetry-http = { version = "0.27.0", optional = true }
opentelemetry-otlp = { version = "0.27.0", optional = true }
opentelemetry-semantic-conventions = { version = "0.27.0", optional = true }
opentelemetry_sdk = { version = "0.27.1", features = [
"rt-tokio",
], optional = true }
reqwest-middleware = { version = "0.4.0", optional = true }
tracing-opentelemetry = { version = "0.28.0", optional = true }
tracing-subscriber = { version = "0.3.19", features = [
"env-filter",
], optional = true }


[dev-dependencies]
serde_json = "1.0.128"
tokio = { version = "1.43.0", features = ["full"] }

[features]
reqwest = ["dep:reqwest"]
time = ["dep:time"]
telemetry = [
"async-trait",
"http",
"once_cell",
"opentelemetry",
"opentelemetry-appender-tracing",
"opentelemetry-http",
"opentelemetry-otlp",
"opentelemetry-semantic-conventions",
"opentelemetry_sdk",
"reqwest",
"reqwest-middleware",
"tracing-opentelemetry",
"tracing-subscriber",
]

[lints.rust]
dead_code = "warn"
Expand Down
66 changes: 66 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,72 @@

Random rust utility functions and types

## Telemetry

For using this module the feature flag `telemetry` need to be added.
This module contains a set of helpers to work with OpenTelemetry logs, traces and metrics.

### Setup

For setup all that's needed it to run the function `famedly_rust_utils::famedly_rust_utils::telemetry::init_otel`. The function returns a guard that takes care of properly shutting down the providers.

If no configuration is present the exporting of logs traces and metrics is disable and the stdout logging is enable.

The functions on the crate exporting opentelemetry traces should be annotated with `tracing::instrument` to generate a new span for that function. Documentation on this macro can be found on the [here](https://docs.rs/tracing/latest/tracing/attr.instrument.html)

The opentelemetry information is exported using gRPC to and opentelemetry collector. By default the expected endpoint is `http://localhots:4317`
The default level of logging and traces is `info` and the default filter directive is `opentelemetry=off,tonic=off,h2=off,reqwest=info,axum=info,hyper=info,hyper-tls=info,tokio=info,tower=info,josekit=info,openssl=info`

```rust
#[tokio::main]
async fn main() {
let _guard = init_otel(config).unwrap();

}
```


### Propagate the context

A context can be propagated to allow linking the traces from two different services. This is done by injecting the context information on the request and retrieving it on the other service.

#### reqwest

For injecting the current context using the reqwest client we can warp a client on a [reqwest-middleware](https://crates.io/crates/reqwest-middleware) and use the `OtelMiddleware` middleware present on the crate.

```rust
use famedly_rust_utils::telemetry::OtelMiddleware;

let reqwest_client = reqwest::Client::builder().build().unwrap();
let client = reqwest_middleware::ClientBuilder::new(reqwest_client)
// Insert the tracing middleware
.with(OtelMiddleware::default())
.build();
client.get("http://localhost").send().await;
```

### axum

For retrieving a context using axum we can use the `OtelAxumLayer` from [axum_tracing_opentelemetry](https://crates.io/crates/axum-tracing-opentelemetry)

> [!WARNING]
> This only seems to be working using the feature flag `tracing_level_info`. See the [issue](https://github.com/davidB/tracing-opentelemetry-instrumentation-sdk/issues/148)
This layer should run as soon as possible

```rust
use axum_tracing_opentelemetry::middleware::OtelAxumLayer;

Router::new().layer(OtelAxumLayer::default())

```

### Metrics

For adding metrics all that it's needed it to make a trace with specific prefix. The documentation on how it works is [here](https://docs.rs/tracing-opentelemetry/latest/tracing_opentelemetry/struct.MetricsLayer.html#usage)

For adding metrics to axum servers creates like [tower-otel-http-metrics](https://github.com/francoposa/tower-otel-http-metrics)

## Lints

```sh
Expand Down
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ mod level_filter;
#[cfg(feature = "reqwest")]
/// Helpers for [reqwest]
pub mod reqwest;
#[cfg(feature = "telemetry")]
/// Function to setup the telemetry tools
pub mod telemetry;

pub use base_url::{BaseUrl, BaseUrlParseError};
pub use level_filter::LevelFilter;
Expand Down
105 changes: 105 additions & 0 deletions src/telemetry/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
//! OpenTelemetry configuration
//!
//! Module containing the configuration struct for the OpenTelemetry
use std::str::FromStr as _;

use serde::Deserialize;
use url::Url;

use crate::LevelFilter;

const DEFAULT_ENDPOINT: &str = "http://localhost:4317";

/// OpenTelemetry configuration
#[derive(Debug, Deserialize, Clone, Default)]
pub struct OtelConfig {
/// Enables logs on stdout
pub stdout: Option<StdoutLogsConfig>,
/// Configurations for exporting traces, metrics and logs
pub exporter: Option<ExporterConfig>,
}

/// Configuration for exporting OpenTelemetry data
#[derive(Debug, Deserialize, Clone, Default)]
pub struct ExporterConfig {
/// gRPC endpoint for exporting using OTELP
pub endpoint: Option<Url>,
/// Application service name
pub service_name: String,
/// Application version
pub version: String,

/// Logs exporting config
pub logs: Option<ProviderConfig>,
/// Traces exporting config
pub traces: Option<ProviderConfig>,
/// Metrics exporting config
pub metrics: Option<ProviderConfig>,
}

/// Stdout logs configuration
#[derive(Debug, Deserialize, Clone)]
pub struct StdoutLogsConfig {
/// Enables the stdout logs
pub enabled: bool,
/// Level for the crate
pub level: Option<LevelFilter>,
/// Level for the dependencies
pub general_level: Option<LevelFilter>,
}

/// Provider configuration for OpenTelemetry export
#[derive(Debug, Deserialize, Clone, Default)]
pub struct ProviderConfig {
/// Enables provider
pub enabled: bool,
/// Level for the crate
pub level: Option<LevelFilter>,
/// Level for the dependencies
pub general_level: Option<LevelFilter>,
}

impl ProviderConfig {
#[allow(clippy::expect_used)]
pub(crate) fn get_filter(&self, crate_name: &'static str) -> String {
format!(
"{},{}={}",
self.general_level.unwrap_or_default(),
crate_name,
self.level.unwrap_or_default()
)
}
}

impl StdoutLogsConfig {
#[allow(clippy::expect_used)]
pub(crate) fn get_filter(&self, crate_name: &'static str) -> String {
format!(
"{},{}={}",
self.general_level.unwrap_or_default(),
crate_name,
self.level.unwrap_or_default()
)
}
}

impl Default for StdoutLogsConfig {
fn default() -> Self {
Self { enabled: true, level: None, general_level: None }
}
}

impl ExporterConfig {
#[allow(clippy::expect_used)]
pub(crate) fn get_endpoint(&self) -> Url {
self.endpoint
.clone()
.unwrap_or(Url::from_str(DEFAULT_ENDPOINT).expect("Error parsing default endpoint"))
}
}

impl Default for LevelFilter {
fn default() -> Self {
LevelFilter(tracing::level_filters::LevelFilter::INFO)
}
}
Loading

0 comments on commit 5f81383

Please sign in to comment.