Skip to content
This repository was archived by the owner on Sep 17, 2025. It is now read-only.
This repository was archived by the owner on Sep 17, 2025. It is now read-only.

StackdriverExporter with BackgroundThreadTransport will use wrong trace_id #212

@bmenasha

Description

@bmenasha

This diff fixes the issue:

index 22a09e7..50cefa0 100644
--- a/opencensus/trace/exporters/stackdriver_exporter.py
+++ b/opencensus/trace/exporters/stackdriver_exporter.py
@@ -14,6 +14,7 @@

import os

+from collections import defaultdict
from google.cloud.trace.client import Client

 from opencensus.trace import attributes_helper
@@ -146,10 +147,14 @@ class StackdriverExporter(base.Exporter):
 
         # convert to the legacy trace json for easier refactoring
         # TODO: refactor this to use the span data directly
-        trace = span_data.format_legacy_trace_json(span_datas)
 
-        stackdriver_spans = self.translate_to_stackdriver(trace)
-        self.client.batch_write_spans(name, stackdriver_spans)
+        trace_id_sds = defaultdict(list)
+        for sd in span_datas:
+            trace_id_sds[sd.context.trace_id] += [sd]
+        for _, sds  in trace_id_sds.items():
+            trace = span_data.format_legacy_trace_json(sds)
+            stackdriver_spans = self.translate_to_stackdriver(trace)
+            self.client.batch_write_spans(name, stackdriver_spans)
 
     def export(self, span_datas):
         """

Without this patch, the span_data.format_legacy_trace_json method will take the trace_id of the first span_data. But when using a BackgroundThreadTransport we'll be writing multiple span_data objects in batches perhaps from multiple requests and trace_ids.

Thanks for correcting.

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