AppFlowy-Cloud/src/telemetry.rs

57 lines
1.6 KiB
Rust

use actix_web::rt::task::JoinHandle;
use tracing::subscriber::set_global_default;
use tracing::Subscriber;
use tracing_bunyan_formatter::{BunyanFormattingLayer, JsonStorageLayer};
use tracing_log::LogTracer;
use tracing_subscriber::fmt::MakeWriter;
use tracing_subscriber::{layer::SubscriberExt, EnvFilter};
/// Compose multiple layers into a `tracing`'s subscriber.
pub fn get_subscriber<Sink>(
name: String,
env_filter: Option<String>,
sink: Sink,
) -> impl Subscriber + Sync + Send
where
Sink: for<'a> MakeWriter<'a> + Send + Sync + 'static,
{
let env_filter = match env_filter {
None => {
dbg!("Using default env filter");
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"))
},
Some(env_filter) => EnvFilter::new(env_filter),
};
let formatting_layer = BunyanFormattingLayer::new(name, sink);
tracing_subscriber::fmt()
.with_ansi(true)
.with_target(true)
.with_max_level(tracing::Level::TRACE)
.with_thread_ids(false)
.with_file(false)
.pretty()
.finish()
.with(env_filter)
.with(JsonStorageLayer)
.with(formatting_layer)
}
/// Register a subscriber as global default to process span data.
///
/// It should only be called once!
pub fn init_subscriber(subscriber: impl Subscriber + Sync + Send) {
LogTracer::init().expect("Failed to set logger");
set_global_default(subscriber).expect("Failed to set subscriber");
}
pub fn spawn_blocking_with_tracing<F, R>(f: F) -> JoinHandle<R>
where
F: FnOnce() -> R + Send + 'static,
R: Send + 'static,
{
let current_span = tracing::Span::current();
actix_web::rt::task::spawn_blocking(move || current_span.in_scope(f))
}