diff --git a/includes/class-tmdo-logger.php b/includes/class-tmdo-logger.php index 324cf38..feac105 100644 --- a/includes/class-tmdo-logger.php +++ b/includes/class-tmdo-logger.php @@ -16,6 +16,35 @@ if ( ! defined( 'ABSPATH' ) ) { */ class TMDO_Logger { + /** + * Request-scoped correlation id, lazily generated. + * + * @var string|null + */ + private static ?string $trace_id = null; + + /** + * Request-scoped UUIDv4 correlation id. + * + * Every audit row written during one request shares this value so a single + * update_*_meta() call can be traced across entity groups. + * + * @return string UUIDv4. + */ + public static function trace_id(): string { + if ( null === self::$trace_id ) { + try { + $bytes = random_bytes( 16 ); + } catch ( \Throwable $e ) { + $bytes = pack( 'H*', md5( (string) microtime( true ) . wp_generate_password( 16, false ) ) ); + } + $bytes[6] = chr( ( ord( $bytes[6] ) & 0x0f ) | 0x40 ); + $bytes[8] = chr( ( ord( $bytes[8] ) & 0x3f ) | 0x80 ); + self::$trace_id = vsprintf( '%s%s-%s-%s-%s-%s%s%s', str_split( bin2hex( $bytes ), 4 ) ); + } + return self::$trace_id; + } + /** * Log an INFO-level event (event-based signature, used by v2.0.0 engine code). *