Skip to content

How does the library handle spans? #1320

@simplekjl

Description

@simplekjl

General question,

I am currently creating spans to wrap traces for my different user flows but I want to know if the current implementation handle the spans internally or not

    override fun startTrace(traceName: String, initialAttributes: Attributes) {
        // Avoid duplicate spans for same logical name
        if (activeSpans.putIfAbsent(
                traceName,
                SpanHolder(Span.getInvalid(), Scope.noop())
            ) != null
        ) {
            logController.w(javaClass.simpleName) { "Trace '$traceName' already active. Ignoring start." }
            return
        }

        val span = getTracer(SCOPE_DEFAULT)
            .spanBuilder(traceName)
            .setSpanKind(SpanKind.INTERNAL)
            .setAllAttributes(initialAttributes)
            .startSpan()

        val scope = span.makeCurrent()
        activeSpans[traceName] = SpanHolder(span, scope)
        logController.d(javaClass.simpleName) { "Trace started: '$traceName', ID: ${span.spanContext.traceId}" }
    }

    override fun endTrace(traceName: String, finalAttributes: Attributes) {
        val holder = activeSpans.remove(traceName)
        if (holder == null) {
            logController.w(javaClass.simpleName) { "No active trace for '$traceName'. Ignoring end." }
            return
        }
        // Ensure scope is always closed
        try {
            holder.span.setAllAttributes(finalAttributes)
        } finally {
            try {
                holder.scope.close()
            } finally {
                holder.span.end()
            }
        }
        logController.d(javaClass.simpleName) { "Trace ended: '$traceName', ID: ${holder.span.spanContext.traceId}" }
    }

Above my current implementation assuming the library doesn't handle span history.

Is there a easier way achieve this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions