#[derive(Debug, Clone)]
pub struct TelemetrySetup {
pub service_name: String,
pub otlp_endpoint: Option<String>,
pub cloud_trace: bool,
pub capture_content: bool,
}
impl TelemetrySetup {
pub fn new(service_name: impl Into<String>) -> Self {
Self {
service_name: service_name.into(),
otlp_endpoint: None,
cloud_trace: false,
capture_content: false,
}
}
pub fn with_otlp(mut self, endpoint: impl Into<String>) -> Self {
self.otlp_endpoint = Some(endpoint.into());
self
}
pub fn with_cloud_trace(mut self) -> Self {
self.cloud_trace = true;
self
}
pub fn with_content_capture(mut self, capture: bool) -> Self {
self.capture_content = capture;
self
}
pub fn init(self) -> Result<(), Box<dyn std::error::Error>> {
#[cfg(feature = "tracing-support")]
{
let config = rs_genai::telemetry::TelemetryConfig {
logging_enabled: true,
log_filter: std::env::var("RUST_LOG").unwrap_or_else(|_| "info".to_string()),
json_logs: false,
metrics_enabled: false,
metrics_addr: None,
otel_traces: self.otlp_endpoint.is_some() || self.cloud_trace,
otel_metrics: false,
otel_service_name: self.service_name,
otel_gcp_project: None,
};
#[cfg(feature = "otel-otlp")]
if let Some(ref endpoint) = self.otlp_endpoint {
std::env::set_var("OTEL_EXPORTER_OTLP_ENDPOINT", endpoint);
}
let _guard = config.init()?;
std::mem::forget(_guard);
}
#[cfg(not(feature = "tracing-support"))]
{
let _ = self; }
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn telemetry_setup_defaults() {
let setup = TelemetrySetup::new("test-service");
assert_eq!(setup.service_name, "test-service");
assert!(setup.otlp_endpoint.is_none());
assert!(!setup.cloud_trace);
assert!(!setup.capture_content);
}
#[test]
fn telemetry_setup_builder_chain() {
let setup = TelemetrySetup::new("my-service")
.with_otlp("http://localhost:4317")
.with_cloud_trace()
.with_content_capture(true);
assert_eq!(setup.service_name, "my-service");
assert_eq!(
setup.otlp_endpoint.as_deref(),
Some("http://localhost:4317")
);
assert!(setup.cloud_trace);
assert!(setup.capture_content);
}
#[test]
fn telemetry_setup_clone() {
let setup = TelemetrySetup::new("svc").with_otlp("http://otel:4317");
let cloned = setup.clone();
assert_eq!(cloned.service_name, "svc");
assert_eq!(cloned.otlp_endpoint.as_deref(), Some("http://otel:4317"));
}
}