UNPKG

unnbound-logger-sdk

Version:

A structured logging library with TypeScript support using Pino. Provides consistent, well-typed logging with automatic logId, workflowId, traceId, and deploymentId tracking across operational contexts.

42 lines (41 loc) 1.61 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.startSpan = void 0; const uuid_1 = require("uuid"); const storage_1 = require("./storage"); const trace_1 = require("./trace"); const logger_1 = require("./logger"); /** * Starts a span that tracks the duration of a callback * @param spanName - The span name to use for logging * @param callback - The async callback to execute * @returns The result of the callback */ const startSpan = async (spanName, callback, getter) => { const spanId = (0, uuid_1.v4)(); const start = performance.now(); const previous = storage_1.storage.getStore(); return storage_1.storage.run({ ...previous, traceId: previous?.traceId ?? (0, trace_1.getTraceId)(), spanId: previous?.spanId ? `${spanId} ${previous?.spanId}` : spanId, }, async () => { logger_1.logger.info({ ...getLogPayload(getter) }, `${spanName} started.`); try { const result = await callback(); logger_1.logger.info({ ...getLogPayload(getter, { result }), duration: getDuration(start) }, `${spanName} completed.`); return result; } catch (error) { logger_1.logger.error({ ...getLogPayload(getter, { error }), err: error, duration: getDuration(start) }, `${spanName} failed.`); throw error; } }); }; exports.startSpan = startSpan; const getLogPayload = (getter, o) => { if (typeof getter !== 'function') return getter; return getter(o); }; const getDuration = (start) => Math.round(performance.now() - start);