forked from open-telemetry/opentelemetry-rust
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.rs
49 lines (41 loc) · 1.67 KB
/
server.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
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Request, Response, Server};
use opentelemetry::{
global,
sdk::export::trace::stdout,
sdk::{
propagation::TraceContextPropagator,
trace::{Config, Sampler},
},
trace::{Span, Tracer},
};
use std::{convert::Infallible, net::SocketAddr};
async fn handle(req: Request<Body>) -> Result<Response<Body>, Infallible> {
let parent_cx = global::get_text_map_propagator(|propagator| propagator.extract(req.headers()));
let span = global::tracer("example/server").start_from_context("hello", &parent_cx);
span.add_event("handling this...".to_string(), Vec::new());
Ok(Response::new("Hello, World!".into()))
}
fn init_tracer() -> (impl Tracer, stdout::Uninstall) {
global::set_text_map_propagator(TraceContextPropagator::new());
// Install stdout exporter pipeline to be able to retrieve the collected spans.
// For the demonstration, use `Sampler::AlwaysOn` sampler to sample all traces. In a production
// application, use `Sampler::ParentBased` or `Sampler::TraceIdRatioBased` with a desired ratio.
stdout::new_pipeline()
.with_trace_config(Config {
default_sampler: Box::new(Sampler::AlwaysOn),
..Default::default()
})
.install()
}
#[tokio::main]
async fn main() {
let _guard = init_tracer();
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
let make_svc = make_service_fn(|_conn| async { Ok::<_, Infallible>(service_fn(handle)) });
let server = Server::bind(&addr).serve(make_svc);
println!("Listening on {}", addr);
if let Err(e) = server.await {
eprintln!("server error: {}", e);
}
}