azify-logger-client-v2
Version:
Azify Logger Client - Centralized logging for OpenSearch
43 lines (33 loc) • 1.03 kB
JavaScript
const { AsyncLocalStorage } = require('async_hooks')
const als = new AsyncLocalStorage()
function generateId(bytes = 16) {
return require('crypto').randomBytes(bytes).toString('hex')
}
function toTraceId(hex32) {
// ensure 32 hex chars
const h = (hex32 || '').padStart(32, '0').slice(0, 32)
return `${h.substring(0, 8)}-${h.substring(8, 12)}-${h.substring(12, 16)}-${h.substring(16, 20)}-${h.substring(20, 32)}`
}
function startRequestContext(initial = {}) {
const traceHex = initial.traceHex || generateId(16) // 16 bytes -> 32 hex
const spanHex = initial.spanHex || generateId(8) // 8 bytes -> 16 hex
const ctx = {
traceId: toTraceId(traceHex),
spanId: spanHex,
parentSpanId: initial.parentSpanId || null,
requestId: initial.requestId
}
return ctx
}
function runWithRequestContext(ctx, fn) {
return als.run(ctx, fn)
}
function getRequestContext() {
return als.getStore() || null
}
module.exports = {
als,
startRequestContext,
runWithRequestContext,
getRequestContext
}