Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add OpenTelemetry setup function #11

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
67 changes: 67 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,73 @@

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 disabled and the stdout logging is enabled.

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` for the crate and all it's dependencies. This level can be changed through the configuration and, the result filter expression is `general_level,main_crate=level` where `general_level` and `level` come from the configuration and `main_crate` is an argument for the `init_otel` function

```rust
#[tokio::main]
async fn main() {
let _guard = init_otel(&config, env!("CARGO_CRATE_NAME")).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 into the request and retrieving it in another service.

#### reqwest

For injecting the current context using the reqwest client we can wrap a client in a [reqwest-middleware](https://crates.io/crates/reqwest-middleware) and use the `OtelMiddleware` middleware present in this 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 is needed is 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 see crates 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
#[serde(default = "default_level_filter")]
pub level: LevelFilter,
/// Level for the dependencies
#[serde(default = "default_level_filter")]
pub general_level: LevelFilter,
}

/// Provider configuration for OpenTelemetry export
#[derive(Debug, Deserialize, Clone)]
pub struct ProviderConfig {
/// Enables provider
pub enabled: bool,
/// Level for the crate
#[serde(default = "default_level_filter")]
pub level: LevelFilter,
/// Level for the dependencies
#[serde(default = "default_level_filter")]
pub general_level: LevelFilter,
}

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

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

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

impl Default for ProviderConfig {
fn default() -> Self {
Self {
enabled: false,
level: default_level_filter(),
general_level: default_level_filter(),
}
}
}

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"))
}
}

const fn default_level_filter() -> LevelFilter {
LevelFilter(tracing::level_filters::LevelFilter::INFO)
}
Loading
Loading