Anatomy of Flags
In a traceparent header, flags are the last 2 characters:Available Flags
tctx provides two flag constants:The bitmask representing a sampled traceparent. When this bit is set to
1, the trace should be recorded by tracing systems.The bitmask representing a random traceparent. When this bit is set to
1, the trace was generated with cryptographically random IDs.By default,
traceparent.make() sets both flags: FLAG_SAMPLE | FLAG_RANDOM = 0b00000011 = 03 (hex).Working with Flags
The flags field is stored as a number in theTraceparent object:
Checking Flags
Use bitwise AND (&) to check if a specific flag is set:
Setting Flags
Use bitwise OR (|) to set a specific flag:
Clearing Flags
Use bitwise AND with NOT (& ~) to clear a specific flag:
Flag Propagation
When you call.child() on a traceparent, all flags are copied to the child:
W3C Specification Details
The W3C Trace Context specification defines the flags field as follows:Bit 0: Sampled (01)
Bit 0: Sampled (01)
Sampled flag - When set to
1, this trace should be recorded.Per the spec:0= Not sampled (trace should be dropped)1= Sampled (trace should be recorded)
00 of the spec.Bit 1: Random (02)
Bit 1: Random (02)
Random flag - When set to
1, the trace-id and parent-id were generated using cryptographically random values.This is a tctx-specific flag and is set by make() to indicate that the IDs were generated using a cryptographically secure random number generator.Bits 2-7: Reserved
Bits 2-7: Reserved
The remaining 6 bits are reserved for future use and should be set to
0 unless defined by a future version of the specification.Examples
Custom Flag Operations
You can perform custom flag operations using bitwise operators:Conditional Sampling Based on Flags
Debug Flag Information
Helper Functions
tctx provides helper functions for common flag operations:is_sampled()
Returns
true if the sampled flag is setis_randomed()
Returns
true if the random flag is setsample()
Sets the sampled flag
unsample()
Clears the sampled flag
Best Practices
- Use helper functions - Prefer
is_sampled()andsample()over direct bit manipulation - Create child before modifying - Call
.child()before changing flags per the W3C spec - Preserve unknown flags - When modifying flags, use bitwise operations to preserve bits you don’t recognize
- Document custom flags - If you use reserved bits for custom purposes, document them clearly
Related
Sampling Guide
Learn how to control trace sampling
Producer/Consumer Pattern
Understand trace propagation