use tracing_subscriber::EnvFilter;
#[derive(Debug, Clone)]
pub struct TelemetryConfig {
pub service: String,
pub version: String,
pub environment: String,
pub instance_id: String,
}
impl TelemetryConfig {
pub fn from_env(service_name: &str, version: &str) -> Self {
let environment = std::env::var("KRAB_ENVIRONMENT").unwrap_or_else(|_| "dev".to_string());
let hostname = std::env::var("HOSTNAME")
.or_else(|_| std::env::var("COMPUTERNAME"))
.unwrap_or_else(|_| "unknown".to_string());
let pid = std::process::id();
Self {
service: std::env::var("KRAB_SERVICE_NAME")
.unwrap_or_else(|_| service_name.to_string()),
version: version.to_string(),
environment,
instance_id: format!("{}.{}", hostname, pid),
}
}
}
#[deprecated(
since = "0.6.0",
note = "logs krab_core's version as the service version; call \
`init_tracing_with_version(name, env!(\"CARGO_PKG_VERSION\"))` so the \
version is expanded in your crate"
)]
pub fn init_tracing(service_name: &str) {
init_tracing_with_version(service_name, env!("CARGO_PKG_VERSION"));
}
pub fn init_tracing_with_version(service_name: &str, version: &str) {
let cfg = TelemetryConfig::from_env(service_name, version);
init_tracing_with_config(&cfg);
}
pub fn init_tracing_with_config(cfg: &TelemetryConfig) {
let filter = std::env::var("RUST_LOG")
.ok()
.and_then(|s| EnvFilter::try_new(s).ok())
.unwrap_or_else(|| EnvFilter::new("info"));
if let Err(error) = tracing_subscriber::fmt()
.json()
.flatten_event(true)
.with_env_filter(filter)
.with_current_span(false)
.with_target(true)
.try_init()
{
tracing::warn!(error = %error, "tracing_subscriber_already_initialised");
}
tracing::info!(
service = %cfg.service,
version = %cfg.version,
environment = %cfg.environment,
instance_id = %cfg.instance_id,
krab.version = env!("CARGO_PKG_VERSION"),
"service_started"
);
}
#[derive(Debug, Clone)]
#[deprecated(
since = "0.6.0",
note = "nothing in Krab populates or reads this per-request telemetry struct; request ids and route labels are attached by the HTTP layers, and metrics live on RuntimeState and /metrics/prometheus. Removed in 0.7.0"
)]
pub struct RequestTelemetry {
pub trace_id: String,
pub request_id: String,
pub service: String,
pub route: String,
pub tenant: Option<String>,
pub user_id: Option<String>,
}
#[allow(deprecated)]
impl RequestTelemetry {
pub fn new(
trace_id: impl Into<String>,
request_id: impl Into<String>,
service: impl Into<String>,
route: impl Into<String>,
) -> Self {
Self {
trace_id: trace_id.into(),
request_id: request_id.into(),
service: service.into(),
route: route.into(),
tenant: None,
user_id: None,
}
}
}
#[derive(Debug, Clone, Default)]
#[deprecated(
since = "0.6.0",
note = "nothing in Krab populates or reads this RED metrics snapshot; request ids and route labels are attached by the HTTP layers, and metrics live on RuntimeState and /metrics/prometheus. Removed in 0.7.0"
)]
pub struct RedMetrics {
pub total_requests: u64,
pub total_errors: u64,
pub duration_sum_ms: u64,
pub duration_max_ms: u64,
}
#[derive(Debug, Clone)]
#[deprecated(
since = "0.6.0",
note = "nothing in Krab populates or reads this per-endpoint RED tracker; request ids and route labels are attached by the HTTP layers, and metrics live on RuntimeState and /metrics/prometheus. Removed in 0.7.0"
)]
#[allow(deprecated)]
pub struct EndpointMetrics {
pub route_pattern: String,
pub red: RedMetrics,
}
#[allow(deprecated)]
impl EndpointMetrics {
pub fn new(route_pattern: impl Into<String>) -> Self {
Self {
route_pattern: route_pattern.into(),
red: RedMetrics::default(),
}
}
pub fn record(&mut self, duration_ms: u64, is_error: bool) {
self.red.total_requests += 1;
self.red.duration_sum_ms += duration_ms;
if duration_ms > self.red.duration_max_ms {
self.red.duration_max_ms = duration_ms;
}
if is_error {
self.red.total_errors += 1;
}
}
}
#[cfg(test)]
#[allow(deprecated)]
mod tests {
use super::*;
use serial_test::serial;
#[test]
#[serial]
fn telemetry_config_from_env_uses_overrides() {
std::env::set_var("KRAB_SERVICE_NAME", "service_override");
std::env::set_var("KRAB_ENVIRONMENT", "staging");
let cfg = TelemetryConfig::from_env("service_default", "1.2.3");
assert_eq!(cfg.service, "service_override");
assert_eq!(cfg.environment, "staging");
assert_eq!(cfg.version, "1.2.3");
assert!(!cfg.instance_id.is_empty());
std::env::remove_var("KRAB_SERVICE_NAME");
std::env::remove_var("KRAB_ENVIRONMENT");
}
#[test]
fn request_telemetry_new_sets_expected_defaults() {
let telemetry = RequestTelemetry::new("trace-1", "req-1", "svc", "/health");
assert_eq!(telemetry.trace_id, "trace-1");
assert_eq!(telemetry.request_id, "req-1");
assert_eq!(telemetry.service, "svc");
assert_eq!(telemetry.route, "/health");
assert!(telemetry.tenant.is_none());
assert!(telemetry.user_id.is_none());
}
#[test]
fn endpoint_metrics_record_updates_red_counters() {
let mut endpoint = EndpointMetrics::new("GET /api/v1/ping");
endpoint.record(10, false);
endpoint.record(30, true);
assert_eq!(endpoint.red.total_requests, 2);
assert_eq!(endpoint.red.total_errors, 1);
assert_eq!(endpoint.red.duration_sum_ms, 40);
assert_eq!(endpoint.red.duration_max_ms, 30);
}
}