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 10, 2025
1 parent 7762eab commit 85d0e49
Show file tree
Hide file tree
Showing 6 changed files with 580 additions and 0 deletions.
36 changes: 36 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,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.85", 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 = { version = "0.12.12", 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]
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 @@ -5,6 +5,9 @@ mod base_url;
pub mod duration;
/// [serde::Deserialize] impl for [tracing::level_filters::LevelFilter]
mod level_filter;
#[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
103 changes: 103 additions & 0 deletions src/telemetry/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
//! 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_FILTER: &str = "opentelemetry=warn,tonic=warn,h2=warn,reqwest=info,axum=info,hyper=info,hyper-tls=info,tokio=info,tower=info,josekit=info,openssl=info";
const DEFAULT_LEVEL: &str = "info";
const DEFAULT_ENDPOINT: &str = "http://localhost:4317";

/// OpenTelemetry configuration
#[derive(Debug, Deserialize, Clone)]
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 logger: Option<ProviderConfig>,
/// Traces exporting config
pub tracer: Option<ProviderConfig>,
/// Metrics exporting config
pub meter: Option<ProviderConfig>,
}

/// Stdout logs configuration
#[derive(Debug, Deserialize, Clone)]
pub struct StdoutLogsConfig {
/// Enables the stdout logs
pub enabled: bool,
/// Level for the filter
pub level: Option<LevelFilter>,
/// Filter directives to change the level on other crates
pub filter_directives: Option<String>,
}

/// Provider configuration for OpenTelemetry export
#[derive(Debug, Deserialize, Clone, Default)]
pub struct ProviderConfig {
/// Enables provider
pub enabled: bool,
/// Level for the filter
pub level: Option<LevelFilter>,
/// Filter directives to change the level on other crates
pub filter_directives: Option<String>,
}

impl ProviderConfig {
#[allow(clippy::expect_used)]
pub(crate) fn get_filter(&self) -> String {
format!(
"{},{}",
self.level.unwrap_or(
LevelFilter::from_str(DEFAULT_LEVEL).expect("Error parsing default level")
),
self.filter_directives.as_ref().unwrap_or(&DEFAULT_FILTER.to_owned())
)
}
}

impl StdoutLogsConfig {
#[allow(clippy::expect_used)]
pub(crate) fn get_filter(&self) -> String {
format!(
"{},{}",
self.level.unwrap_or(
LevelFilter::from_str(DEFAULT_LEVEL).expect("Error parsing default level")
),
self.filter_directives.as_ref().unwrap_or(&DEFAULT_FILTER.to_owned())
)
}
}

impl Default for StdoutLogsConfig {
fn default() -> Self {
Self { enabled: true, level: None, filter_directives: 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"))
}
}
Loading

0 comments on commit 85d0e49

Please sign in to comment.