Module Contents

_common_invalid_name_characters = ?;*()!$~^<>
ORIGIN_TRACE_HEADER_ATTR_KEY = _origin_trace_header
class Entity(name)


The parent class for segment/subsegment. It holds common properties and methods on segment and subsegment.

close(self, end_time=None)

Close the trace entity by setting end_time and flip the in progress flag to False.

Parameters:end_time (int) – Epoch in seconds. If not specified current time will be used.
add_subsegment(self, subsegment)

Add input subsegment as a child subsegment.

remove_subsegment(self, subsegment)

Remove input subsegment from child subsegments.

put_http_meta(self, key, value)

Add http related metadata.

  • key (str) – Currently supported keys are: * url * method * user_agent * client_ip * status * content_length
  • value – status and content_length are int and for other supported keys string should be used.
put_annotation(self, key, value)

Annotate segment or subsegment with a key-value pair. Annotations will be indexed for later search query.

  • key (str) – annotation key
  • value (object) – annotation value. Any type other than string/number/bool will be dropped
put_metadata(self, key, value, namespace='default')

Add metadata to segment or subsegment. Metadata is not indexed but can be later retrieved by BatchGetTraces API.

  • namespace (str) – optional. Default namespace is default. It must be a string and prefix AWS. is reserved.
  • key (str) – metadata key under specified namespace
  • value (object) – any object that can be serialized into JSON string
set_aws(self, aws_meta)

set aws section of the entity. This method is called by global recorder and botocore patcher to provide additonal information about AWS runtime. It is not recommended to manually set aws section.

apply_status_code(self, status_code)

When a trace entity is generated under the http context, the status code will affect this entity’s fault/error/throttle flags. Flip these flags based on status code.

add_exception(self, exception, stack, remote=False)

Add an exception to trace entities.

  • exception (Exception) – the catched exception.
  • stack (list) – the output from python built-in traceback.extract_stack().
  • remote (bool) – If False it means it’s a client error instead of a downstream service.
save_origin_trace_header(self, trace_header)

Temporarily store additional data fields in trace header to the entity for later propagation. The data will be cleaned up upon serialization.


Retrieve saved trace header data.


Serialize to JSON document that can be accepted by the X-Ray backend service. It uses jsonpickle to perform serialization.

_delete_empty_properties(self, properties)

Delete empty properties before serialization to avoid extra keys with empty values in the output json.


Generate a random 16-digit hex str. This is used for generating segment/subsegment id.