Advanced Tracing
This page covers advanced tracing topics, including manual context propagation and adding custom metadata to your traces.
Context Propagation
Tracy handles context propagation automatically when using structured coroutines or annotated functions. However, certain concurrency patterns (runBlocking, raw threads) require manual propagation. See Limitations for details on when manual propagation is needed.
Kotlin Coroutines
Context propagation works automatically with withContext, launch, and async. But some models like runBlocking or raw threads create boundaries that require manual propagation.
See the full examples: ContextPropagationExample.kt
runBlocking
Use currentSpanContextElement to ensure child spans are linked to their parent when using runBlocking inside a suspend function.
@Trace
suspend fun processRequest() {
runBlocking(currentSpanContextElement(currentCoroutineContext())) {
// Nested spans will be correctly linked
}
}
Multi-Threading
Standard threads do NOT inherit the OpenTelemetry context. You must capture and propagate it manually:
suspend fun processInThread() {
val context = currentSpanContext(currentCoroutineContext())
thread {
context.makeCurrent().use {
// Your code here will be part of the same trace
}
}
}
Custom Tags
You can enrich your traces with business-specific metadata using custom tags. These tags are especially useful for filtering and grouping traces in tools like Langfuse.
Adding Langfuse Tags
Use addLangfuseTagsToCurrentTrace to attach tags dynamically within any traced function.
fun myBusinessLogic() {
addLangfuseTagsToCurrentTrace(listOf("user-tier:premium", "feature:search"))
// ...
}
See the full example: LangfuseTagExample.kt
Best Practices
- Use structured concurrency: Prefer Kotlin coroutines over raw threads to benefit from automatic context propagation.
- Redact by default: Be mindful of PII (Personally Identifiable Information) and only enable sensitive content capture when necessary.
- Tag for success: Use custom tags to make your traces easier to analyze in the backend.