How to get parent span id from span

I want to get some information from apm SpanContext to log in my logs, but I only can get transcationId, traceId and spanId, how to get the parent span id?

The code come from apmlogrus

// TraceContext returns a logrus.Fields containing the trace
// context of the transaction and span contained in ctx, if any.
func TraceContext(ctx context.Context) logrus.Fields {
	tx := apm.TransactionFromContext(ctx)
	if tx == nil {
		return nil
	}
	traceContext := tx.TraceContext()
	fields := logrus.Fields{
		FieldKeyTraceID:       traceContext.Trace,
		FieldKeyTransactionID: traceContext.Span,
	}
	if span := apm.SpanFromContext(ctx); span != nil {
		fields[FieldKeySpanID] = span.TraceContext().Span
	}
	return fields
}

Welcome to the forum @peng_xing!

It is not currently possible to extract the parent ID from a transaction or span. Could you explain why you want to log the parent span ID? We might consider adding way to access it.

I want to record the tracing information in the logs. The most import fields I think are traceId,spanId and parentSpanId. But TraceContext method only provides traceId and spanId fields.
It is worth mentioning that we are not using elastic stack to store logs currently, only using elastic apm feature.

OK. What you would would use the parent ID field in your logs for? The fields (trace.id, span.id) that apmlogrus adds to logs will give you enough information to correlate log records with their associated spans. You can then link from that span to its parent in ES.

You can then link from that span to its parent in ES.

Yes, but I think maybe recording parent span id in the logs is a more convenient way, right?

I agreed that trace.id and span.id are enough information to correlate logs records. But I think the context of tracing should include parent id.

I don't think we'll change the log integrations to add parent.id to the log fields, but we could add methods to Transaction and Span to fetch the parent ID. You could then write some custom code to inject parent.id into your logs. Would that work for you?

That's great. Thank you

I've opened an issue on GitHub to track this enhancement: Introduce a way to extract the parent ID from Transactions and Spans · Issue #909 · elastic/apm-agent-go · GitHub

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.