UNPKG

kobp

Version:
68 lines 1.85 kB
import { randomBytes } from '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')) * } * } * ) * ``` */ export 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 }; } } /** * 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)}.${randomBytes(4).toString('hex').substring(0, 4)}`; } return `${currentKey}>${randomBytes(4).toString('hex').substring(0, 4)}`; } }; //# sourceMappingURL=tracer.js.map