|
| 1 | +use actix_service::Service; |
| 2 | +use actix_web::middleware::Logger; |
| 3 | +use actix_web::{web, App, HttpServer}; |
| 4 | +use opentelemetry::api::{Key, TraceContextExt, Tracer}; |
| 5 | +use opentelemetry::sdk::BatchSpanProcessor; |
| 6 | +use opentelemetry::{global, sdk}; |
| 7 | +use opentelemetry::api::trace::futures::FutureExt; |
| 8 | + |
| 9 | +fn init_tracer() -> thrift::Result<()> { |
| 10 | + let exporter = opentelemetry_jaeger::Exporter::builder() |
| 11 | + .with_collector_endpoint("http://127.0.0.1:14268/api/traces") |
| 12 | + .with_process(opentelemetry_jaeger::Process { |
| 13 | + service_name: "trace-http-demo".to_string(), |
| 14 | + tags: vec![ |
| 15 | + Key::new("exporter").string("jaeger"), |
| 16 | + Key::new("float").f64(312.23), |
| 17 | + ], |
| 18 | + }) |
| 19 | + .init()?; |
| 20 | + |
| 21 | + let batch_exporter = BatchSpanProcessor::builder(exporter, tokio::spawn, tokio::time::interval) |
| 22 | + .build(); |
| 23 | + |
| 24 | + let provider = sdk::Provider::builder() |
| 25 | + .with_batch_exporter(batch_exporter) |
| 26 | + .with_config(sdk::Config { |
| 27 | + default_sampler: Box::new(sdk::Sampler::Always), |
| 28 | + ..Default::default() |
| 29 | + }) |
| 30 | + .build(); |
| 31 | + global::set_provider(provider); |
| 32 | + |
| 33 | + Ok(()) |
| 34 | +} |
| 35 | + |
| 36 | +async fn index() -> &'static str { |
| 37 | + let tracer = global::tracer("request"); |
| 38 | + tracer.in_span("index", |ctx| { |
| 39 | + ctx.span().set_attribute(Key::new("parameter").i64(10)); |
| 40 | + "Index" |
| 41 | + }) |
| 42 | +} |
| 43 | + |
| 44 | +#[actix_rt::main] |
| 45 | +async fn main() -> std::io::Result<()> { |
| 46 | + std::env::set_var("RUST_LOG", "debug"); |
| 47 | + env_logger::init(); |
| 48 | + init_tracer().expect("Failed to initialise tracer."); |
| 49 | + |
| 50 | + HttpServer::new(|| { |
| 51 | + App::new() |
| 52 | + .wrap(Logger::default()) |
| 53 | + .wrap_fn(|req, srv| { |
| 54 | + let tracer = global::tracer("request"); |
| 55 | + tracer.in_span("middleware", move |cx| { |
| 56 | + cx.span().set_attribute(Key::new("path").string(req.path())); |
| 57 | + srv.call(req).with_context(cx) |
| 58 | + }) |
| 59 | + }) |
| 60 | + .route("/", web::get().to(index)) |
| 61 | + }) |
| 62 | + .bind("127.0.0.1:8088") |
| 63 | + .unwrap() |
| 64 | + .run() |
| 65 | + .await |
| 66 | +} |
0 commit comments