Skip to content

Commit

Permalink
Fix the issue of duplicate traceId and spanId caused by RandomIdGener…
Browse files Browse the repository at this point in the history
…ator.
  • Loading branch information
lyred193 committed Jan 3, 2025
1 parent 29aad2e commit 22a5a84
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
11 changes: 7 additions & 4 deletions opentelemetry-sdk/src/opentelemetry/sdk/trace/id_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,17 @@ class RandomIdGenerator(IdGenerator):
bits when generating IDs.
"""

def __init__(self):
self._rand = random.Random()

def generate_span_id(self) -> int:
span_id = random.getrandbits(64)
span_id = self._rand.getrandbits(64)
while span_id == trace.INVALID_SPAN_ID:
span_id = random.getrandbits(64)
span_id = self._rand.getrandbits(64)
return span_id

def generate_trace_id(self) -> int:
trace_id = random.getrandbits(128)
trace_id = self._rand.getrandbits(128)
while trace_id == trace.INVALID_TRACE_ID:
trace_id = random.getrandbits(128)
trace_id = self._rand.getrandbits(128)
return trace_id
15 changes: 15 additions & 0 deletions opentelemetry-sdk/tests/trace/test_id_generator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import unittest

from opentelemetry.sdk.trace import RandomIdGenerator


class TestIdGenerator(unittest.TestCase):

def test_random_id_generator(self):
import random
random.seed(10)
id_generator = RandomIdGenerator()
trace_id = id_generator.generate_trace_id()
span_id = id_generator.generate_span_id()
self.assertNotEqual(trace_id, 164207228320579316746596838417247989971)
self.assertNotEqual(span_id, 273610340023782072)

0 comments on commit 22a5a84

Please sign in to comment.