-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tracer.rs
66 lines (55 loc) · 2.17 KB
/
tracer.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//! Opentelemetry tracing extensions and setup.
use crate::settings::Otel;
use anyhow::{anyhow, Result};
use const_format::formatcp;
use http::Uri;
use opentelemetry::global;
use opentelemetry_otlp::{TonicExporterBuilder, WithExportConfig};
use opentelemetry_sdk::{
propagation::TraceContextPropagator,
runtime,
trace::{self, Tracer},
Resource,
};
use opentelemetry_semantic_conventions as otel_semcov;
use tonic::{metadata::MetadataMap, transport::ClientTlsConfig};
//const PKG_NAME: &str = env!("CARGO_PKG_NAME");
const PKG_NAME: &str = "application";
const VERSION: &str = formatcp!("v{}", env!("CARGO_PKG_VERSION"));
const LANG: &str = "rust";
/// Initialize Opentelemetry tracing via the [OTLP protocol].
///
/// [OTLP protocol]: <https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/otlp.md>
pub fn init_tracer(settings: &Otel) -> Result<Tracer> {
global::set_text_map_propagator(TraceContextPropagator::new());
let resource = Resource::new(vec![
otel_semcov::resource::SERVICE_NAME.string(PKG_NAME),
otel_semcov::resource::SERVICE_VERSION.string(VERSION),
otel_semcov::resource::TELEMETRY_SDK_LANGUAGE.string(LANG),
]);
let endpoint = &settings.exporter_otlp_endpoint;
let map = MetadataMap::with_capacity(2);
let trace = opentelemetry_otlp::new_pipeline()
.tracing()
.with_exporter(exporter(map, endpoint)?)
.with_trace_config(trace::config().with_resource(resource))
.install_batch(runtime::Tokio)
.map_err(|e| anyhow!("failed to intialize tracer: {:#?}", e))?;
Ok(trace)
}
fn exporter(map: MetadataMap, endpoint: &Uri) -> Result<TonicExporterBuilder> {
// Over grpc transport
let exporter = opentelemetry_otlp::new_exporter()
.tonic()
.with_endpoint(endpoint.to_string())
.with_metadata(map);
match endpoint.scheme_str() {
Some("https") => {
let host = endpoint
.host()
.ok_or_else(|| anyhow!("failed to parse host"))?;
Ok(exporter.with_tls_config(ClientTlsConfig::new().domain_name(host.to_string())))
}
_ => Ok(exporter),
}
}