| 1 |
import os |
| 2 |
import time |
| 3 |
import binascii |
| 4 |
|
| 5 |
|
| 6 |
class TraceId: |
| 7 |
""" |
| 8 |
A trace ID tracks the path of a request through your application. |
| 9 |
A trace collects all the segments generated by a single request. |
| 10 |
A trace ID is required for a segment. |
| 11 |
""" |
| 12 |
VERSION = '1' |
| 13 |
DELIMITER = '-' |
| 14 |
|
| 15 |
def __init__(self): |
| 16 |
""" |
| 17 |
Generate a random trace id. |
| 18 |
""" |
| 19 |
self.start_time = int(time.time()) |
| 20 |
self.__number = binascii.b2a_hex(os.urandom(12)).decode('utf-8') |
| 21 |
|
| 22 |
def to_id(self): |
| 23 |
""" |
| 24 |
Convert TraceId object to a string. |
| 25 |
""" |
| 26 |
return "%s%s%s%s%s" % (TraceId.VERSION, TraceId.DELIMITER, |
| 27 |
format(self.start_time, 'x'), |
| 28 |
TraceId.DELIMITER, self.__number) |