UNPKG

kobp

Version:
72 lines 1.99 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Tracer = void 0; const crypto_1 = require("crypto"); /** * Tracer Usage * * Extends this class. And initialize this with beforeFork middlewares * * Example: * ```ts * * class CustomTracer extends Tracer { * ** my own functions ** * } * * makeServer( * ..., * { * middlewareBeforeFork: (app) => { * app.use((ctx, next) => { * ctx.tracer = new CustomTracer(ctx) * await next() * }) * }, * middlewareAfterFork: (app) => { * app.use(Tracer.attach('tracer')) * } * } * ) * ``` */ class Tracer { /** * * will be called automatically when the context is created */ constructor(ctx) { const config = Tracer._config; const fromHeader = ctx.request.headers[config.requestTraceHeaderKey]; const sanitized = (typeof fromHeader === 'string' ? fromHeader : (fromHeader && fromHeader.length > 0 && fromHeader[0] || '')); this.traceId = config.traceIdMaker(sanitized); this.context = ctx; this.context.traceId = this.traceId; } /** * Update tracer's configuration. You should call this only once. * * @param config */ static config(config) { this._config = { ...this._config, ...config }; } } exports.Tracer = Tracer; /** * Access this parameter to customize the Tracer behavior */ Tracer._config = { requestTraceHeaderKey: 'x-trace-id', traceIdMaker: (currentKey) => { // Stack key when current ray run through multiple services. if (!currentKey) { return `${new Date().getTime().toString(32)}.${(0, crypto_1.randomBytes)(4).toString('hex').substring(0, 4)}`; } return `${currentKey}>${(0, crypto_1.randomBytes)(4).toString('hex').substring(0, 4)}`; } }; //# sourceMappingURL=tracer.js.map