use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::{fmt, EnvFilter};
pub enum LogMode {
Cli,
Proxy,
}
#[cfg(feature = "sentry")]
pub type SentryGuard = sentry::ClientInitGuard;
#[cfg(not(feature = "sentry"))]
pub type SentryGuard = ();
pub fn init(mode: LogMode, verbose: bool) -> Option<SentryGuard> {
let filter = match std::env::var("RUST_LOG") {
Ok(val) if !val.is_empty() => EnvFilter::from_default_env(),
_ if verbose => EnvFilter::new("debug"),
_ => EnvFilter::new("info"),
};
let sentry_guard = init_sentry();
let registry = tracing_subscriber::registry().with(filter);
#[cfg(feature = "sentry")]
let registry = registry.with(sentry_guard.as_ref().map(|_| sentry_tracing::layer()));
match mode {
LogMode::Proxy => {
registry
.with(
fmt::layer()
.json()
.flatten_event(true)
.with_writer(std::io::stderr)
.with_target(true)
.with_current_span(false),
)
.init();
}
LogMode::Cli => {
registry
.with(
fmt::layer()
.compact()
.with_writer(std::io::stderr)
.with_target(false),
)
.init();
}
}
#[cfg(not(feature = "sentry"))]
if std::env::var("SENTRY_DSN").is_ok() || std::env::var("GREP_SENTRY_DSN").is_ok() {
tracing::warn!(
"SENTRY_DSN is set but this binary was compiled without the sentry feature — ignoring. \
Build with: cargo build --features sentry"
);
}
sentry_guard
}
#[cfg(feature = "sentry")]
pub fn shutdown(guard: Option<SentryGuard>) {
drop(guard);
}
#[cfg(not(feature = "sentry"))]
#[inline]
pub fn shutdown(_guard: Option<SentryGuard>) {}
fn init_sentry() -> Option<SentryGuard> {
#[cfg(feature = "sentry")]
{
let dsn = std::env::var("GREP_SENTRY_DSN")
.or_else(|_| std::env::var("SENTRY_DSN"))
.ok()?;
let environment =
std::env::var("ENVIRONMENT_TIER").unwrap_or_else(|_| "development".into());
match environment.as_str() {
"production" | "staging" | "demo" => {}
_ => {
tracing::debug!(environment = %environment, "sentry disabled for this environment");
return None;
}
}
let service = std::env::var("SERVICE_NAME").unwrap_or_else(|_| "ati-proxy".into());
let sample_rate = match environment.as_str() {
"production" => 0.25,
"staging" => 0.5,
_ => 1.0,
};
let sentry_debug = std::env::var("ATI_SENTRY_DEBUG")
.map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
.unwrap_or(false);
let guard = sentry::init((
dsn,
sentry::ClientOptions {
release: Some(env!("CARGO_PKG_VERSION").into()),
environment: Some(environment.into()),
server_name: Some(service.into()),
traces_sample_rate: sample_rate,
attach_stacktrace: true,
send_default_pii: false,
debug: sentry_debug,
..Default::default()
},
));
if guard.is_enabled() {
Some(guard)
} else {
None
}
}
#[cfg(not(feature = "sentry"))]
{
None
}
}