-
Notifications
You must be signed in to change notification settings - Fork 460
/
main.rs
162 lines (138 loc) · 5.9 KB
/
main.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
/// To use hyper as the HTTP client - cargo run --features="hyper" --no-default-features
use once_cell::sync::Lazy;
use opentelemetry::{
global,
trace::{TraceContextExt, TraceError, Tracer},
InstrumentationScope, KeyValue,
};
use opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge;
use opentelemetry_otlp::WithExportConfig;
use opentelemetry_otlp::{LogExporter, MetricExporter, Protocol, SpanExporter};
use opentelemetry_sdk::{
logs::LoggerProvider,
metrics::{MetricError, SdkMeterProvider},
trace::{self as sdktrace, TracerProvider},
};
use opentelemetry_sdk::{
logs::{self as sdklogs},
Resource,
};
use std::error::Error;
use tracing::info;
use tracing_subscriber::prelude::*;
use tracing_subscriber::EnvFilter;
static RESOURCE: Lazy<Resource> = Lazy::new(|| {
Resource::builder()
.with_service_name("basic-otlp-example")
.build()
});
fn init_logs() -> Result<sdklogs::LoggerProvider, opentelemetry_sdk::logs::LogError> {
let exporter = LogExporter::builder()
.with_http()
.with_endpoint("http://localhost:4318/v1/logs")
.with_protocol(Protocol::HttpBinary)
.build()?;
Ok(LoggerProvider::builder()
.with_batch_exporter(exporter)
.with_resource(RESOURCE.clone())
.build())
}
fn init_traces() -> Result<sdktrace::TracerProvider, TraceError> {
let exporter = SpanExporter::builder()
.with_http()
.with_protocol(Protocol::HttpBinary) //can be changed to `Protocol::HttpJson` to export in JSON format
.with_endpoint("http://localhost:4318/v1/traces")
.build()?;
Ok(TracerProvider::builder()
.with_batch_exporter(exporter)
.with_resource(RESOURCE.clone())
.build())
}
fn init_metrics() -> Result<opentelemetry_sdk::metrics::SdkMeterProvider, MetricError> {
let exporter = MetricExporter::builder()
.with_http()
.with_protocol(Protocol::HttpBinary) //can be changed to `Protocol::HttpJson` to export in JSON format
.with_endpoint("http://localhost:4318/v1/metrics")
.build()?;
let reader = opentelemetry_sdk::metrics::PeriodicReader::builder(exporter).build();
Ok(SdkMeterProvider::builder()
.with_reader(reader)
.with_resource(RESOURCE.clone())
.build())
}
// #[tokio::main]
// TODO: Re-enable tokio::main, if needed, after
fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
let logger_provider = init_logs()?;
// Create a new OpenTelemetryTracingBridge using the above LoggerProvider.
let otel_layer = OpenTelemetryTracingBridge::new(&logger_provider);
// For the OpenTelemetry layer, add a tracing filter to filter events from
// OpenTelemetry and its dependent crates (opentelemetry-otlp uses crates
// like reqwest/tonic etc.) from being sent back to OTel itself, thus
// preventing infinite telemetry generation. The filter levels are set as
// follows:
// - Allow `info` level and above by default.
// - Restrict `opentelemetry`, `hyper`, `tonic`, and `reqwest` completely.
// Note: This will also drop events from crates like `tonic` etc. even when
// they are used outside the OTLP Exporter. For more details, see:
// https://github.com/open-telemetry/opentelemetry-rust/issues/761
let filter_otel = EnvFilter::new("info")
.add_directive("hyper=off".parse().unwrap())
.add_directive("opentelemetry=off".parse().unwrap())
.add_directive("tonic=off".parse().unwrap())
.add_directive("h2=off".parse().unwrap())
.add_directive("reqwest=off".parse().unwrap());
let otel_layer = otel_layer.with_filter(filter_otel);
// Create a new tracing::Fmt layer to print the logs to stdout. It has a
// default filter of `info` level and above, and `debug` and above for logs
// from OpenTelemetry crates. The filter levels can be customized as needed.
let filter_fmt = EnvFilter::new("info").add_directive("opentelemetry=debug".parse().unwrap());
let fmt_layer = tracing_subscriber::fmt::layer()
.with_thread_names(true)
.with_filter(filter_fmt);
// Initialize the tracing subscriber with the OpenTelemetry layer and the
// Fmt layer.
tracing_subscriber::registry()
.with(otel_layer)
.with(fmt_layer)
.init();
let tracer_provider = init_traces()?;
global::set_tracer_provider(tracer_provider.clone());
let meter_provider = init_metrics()?;
global::set_meter_provider(meter_provider.clone());
let common_scope_attributes = vec![KeyValue::new("scope-key", "scope-value")];
let scope = InstrumentationScope::builder("basic")
.with_version("1.0")
.with_attributes(common_scope_attributes)
.build();
let tracer = global::tracer_with_scope(scope.clone());
let meter = global::meter_with_scope(scope);
let counter = meter
.u64_counter("test_counter")
.with_description("a simple counter for demo purposes.")
.with_unit("my_unit")
.build();
for _ in 0..10 {
counter.add(1, &[KeyValue::new("test_key", "test_value")]);
}
counter.add(1, &[KeyValue::new("test_key", "test_value")]);
tracer.in_span("Main operation", |cx| {
let span = cx.span();
span.add_event(
"Nice operation!".to_string(),
vec![KeyValue::new("some.key", 100)],
);
span.set_attribute(KeyValue::new("another.key", "yes"));
info!(target: "my-target", "hello from {}. My price is {}. I am also inside a Span!", "banana", 2.99);
tracer.in_span("Sub operation...", |cx| {
let span = cx.span();
span.set_attribute(KeyValue::new("another.key", "yes"));
span.add_event("Sub span event", vec![]);
});
});
info!(target: "my-target", "hello from {}. My price is {}", "apple", 1.99);
tracer_provider.shutdown()?;
logger_provider.shutdown()?;
meter_provider.shutdown()?;
Ok(())
}