Try fixing span context for db call tracing

This commit is contained in:
Cameron
2025-06-03 12:51:37 -04:00
parent 1e63e0c08c
commit b11d647ffa

View File

@@ -3,7 +3,7 @@ use actix_web::HttpRequest;
use opentelemetry::global::BoxedTracer;
use opentelemetry::{global, Context, KeyValue};
use opentelemetry::propagation::TextMapPropagator;
use opentelemetry::trace::Tracer;
use opentelemetry::trace::{Status, TraceContextExt, Tracer};
use opentelemetry_appender_log::OpenTelemetryLogBridge;
use opentelemetry_otlp::WithExportConfig;
use opentelemetry_sdk::logs::{BatchLogProcessor, SdkLoggerProvider};
@@ -82,15 +82,26 @@ pub fn extract_context_from_request(req: &HttpRequest) -> Context {
propagator.extract(&HeaderExtractor(req.headers()))
}
pub fn trace_db_call<F, O>(operation: &str, query_type: &str, func: F) -> anyhow::Result<O>
pub fn trace_db_call<F, O>(query_type: &str, operation: &str, func: F) -> anyhow::Result<O>
where F: FnOnce() -> anyhow::Result<O> {
let tracer = global::tracer("db");
let _span = tracer
.span_builder(format!("db.{}.{}", operation, query_type))
let span = tracer
.span_builder(format!("db.{}.{}", query_type, operation))
.with_attributes(vec![
KeyValue::new("db.operation", operation.to_string().clone()),
KeyValue::new("db.query_type", query_type.to_string().clone()),
KeyValue::new("db.operation", operation.to_string().clone()),
]).start(&tracer);
func()
let context = Context::current_with_span(span);
let result = func();
match &result {
Ok(_) => {
context.span().set_status(Status::Ok);
}
Err(e) => {
context.span().set_status(Status::error(e.to_string()))
}
}
result
}