#include "trace_ctx.h" #include #include #include namespace borla { char TraceCtx::trace_id_[TraceCtx::kIdBufSize] = "-"; char TraceCtx::session_id_[TraceCtx::kIdBufSize] = "-"; char TraceCtx::request_id_[TraceCtx::kIdBufSize] = "-"; static void GenHex16(char* out) { // 16 hex chars from 8 random bytes. uint8_t buf[8]; esp_fill_random(buf, sizeof(buf)); static const char kHex[] = "0123456789abcdef"; for (int i = 0; i < 8; ++i) { out[i * 2] = kHex[(buf[i] >> 4) & 0x0F]; out[i * 2 + 1] = kHex[buf[i] & 0x0F]; } out[16] = '\0'; } const char* TraceCtx::TraceId() { return trace_id_; } const char* TraceCtx::SessionId() { return session_id_; } const char* TraceCtx::RequestId() { return request_id_; } void TraceCtx::RefreshTrace(const char* prefix) { char hex[20]; GenHex16(hex); // 安全拼接到固定缓冲 snprintf(trace_id_, kIdBufSize, "%s-%s", prefix ? prefix : "dev", hex); } void TraceCtx::RefreshSession() { char hex[20]; GenHex16(hex); snprintf(session_id_, kIdBufSize, "s-%s", hex); } const char* TraceCtx::NewRequestId() { char hex[20]; GenHex16(hex); snprintf(request_id_, kIdBufSize, "r-%s", hex); return request_id_; } void TraceCtx::SetTrace(const char* trace_id) { if (!trace_id || !trace_id[0]) return; strncpy(trace_id_, trace_id, kIdBufSize - 1); trace_id_[kIdBufSize - 1] = '\0'; } void TraceCtx::SetSession(const char* session_id) { if (!session_id || !session_id[0]) return; strncpy(session_id_, session_id, kIdBufSize - 1); session_id_[kIdBufSize - 1] = '\0'; } } // namespace borla