|
| 1 | +use opentelemetry::sdk::Resource; |
| 2 | +use opentelemetry::{sdk::trace as sdktrace, trace::TraceError}; |
| 3 | +use opentelemetry_semantic_conventions as semcov; |
| 4 | + |
| 5 | +#[cfg(feature = "jaeger")] |
| 6 | +mod jaeger; |
| 7 | +#[cfg(feature = "otlp")] |
| 8 | +mod otlp; |
| 9 | + |
| 10 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 11 | +pub enum CollectorKind { |
| 12 | + #[cfg(feature = "otlp")] |
| 13 | + Otlp, |
| 14 | + #[cfg(feature = "jaeger")] |
| 15 | + Jaeger, |
| 16 | + // Stdout, |
| 17 | +} |
| 18 | + |
| 19 | +#[cfg(any(feature = "jaeger", feature = "otlp"))] |
| 20 | +pub fn init_tracer( |
| 21 | + kind: CollectorKind, |
| 22 | + resource: Resource, |
| 23 | +) -> Result<sdktrace::Tracer, TraceError> { |
| 24 | + match kind { |
| 25 | + #[cfg(feature = "otlp")] |
| 26 | + CollectorKind::Otlp => { |
| 27 | + // if let Some(url) = std::env::var_os("OTEL_COLLECTOR_URL") |
| 28 | + // "http://localhost:14499/otlp/v1/traces" |
| 29 | + // let collector_url = url.to_str().ok_or(TraceError::Other( |
| 30 | + // anyhow!("failed to parse OTEL_COLLECTOR_URL").into(), |
| 31 | + // ))?; |
| 32 | + otlp::init_tracer(resource, otlp::identity) |
| 33 | + } |
| 34 | + #[cfg(feature = "jaeger")] |
| 35 | + CollectorKind::Jaeger => { |
| 36 | + // Or "OTEL_EXPORTER_JAEGER_ENDPOINT" |
| 37 | + // or now variable |
| 38 | + jaeger::init_tracer(resource, jaeger::identity) |
| 39 | + } |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +/// call with service name and version |
| 44 | +/// |
| 45 | +/// ```rust |
| 46 | +/// make_resource(env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")) |
| 47 | +/// ``` |
| 48 | +pub fn make_resource<S>(service_name: S, service_version: S) -> Resource |
| 49 | +where |
| 50 | + S: Into<String>, |
| 51 | +{ |
| 52 | + Resource::new(vec![ |
| 53 | + semcov::resource::SERVICE_NAME.string(service_name.into()), |
| 54 | + semcov::resource::SERVICE_VERSION.string(service_version.into()), |
| 55 | + ]) |
| 56 | +} |
| 57 | + |
| 58 | +/// Search the current opentelemetry trace id into the Context from the current tracing'span. |
| 59 | +/// This function can be used to report the trace id into the error message send back to user. |
| 60 | +pub fn find_current_trace_id() -> Option<String> { |
| 61 | + use opentelemetry::trace::TraceContextExt; |
| 62 | + use tracing_opentelemetry::OpenTelemetrySpanExt; |
| 63 | + // let context = opentelemetry::Context::current(); |
| 64 | + // OpenTelemetry Context is propagation inside code is done via tracing crate |
| 65 | + let context = tracing::Span::current().context(); |
| 66 | + let span = context.span(); |
| 67 | + let span_context = span.span_context(); |
| 68 | + span_context |
| 69 | + .is_valid() |
| 70 | + .then(|| span_context.trace_id().to_string()) |
| 71 | +} |
0 commit comments