unnbound-logger-sdk 3.0.0 → 3.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,9 @@
1
+ import { Axios } from 'axios';
2
+ import { HttpOptions } from './types';
3
+ /**
4
+ * Wraps an axios instance to add tracing and span tracking
5
+ * @param axios - The axios instance to wrap
6
+ * @param options - Configuration options for HTTP tracing
7
+ * @returns The wrapped axios instance with span tracking
8
+ */
9
+ export declare const traceAxios: (client: Axios, { ignoreTraceRoutes, traceHeaderKey, }?: HttpOptions) => Axios;
package/dist/axios.js ADDED
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.traceAxios = void 0;
4
+ const axios_1 = require("axios");
5
+ const types_1 = require("./types");
6
+ const storage_1 = require("./storage");
7
+ const utils_1 = require("./utils");
8
+ const span_1 = require("./span");
9
+ const buildOutgoingHttpPayload = (config, res) => ({
10
+ type: 'http',
11
+ http: {
12
+ url: [config.baseURL, config.url].filter(Boolean).join(''),
13
+ method: config.method?.toUpperCase() || 'GET',
14
+ incoming: false,
15
+ request: {
16
+ headers: config.headers,
17
+ body: (0, utils_1.safeJsonParse)(config.data),
18
+ },
19
+ response: res
20
+ ? {
21
+ headers: res?.headers,
22
+ status: res.status,
23
+ body: (0, utils_1.safeJsonParse)(res.data),
24
+ }
25
+ : undefined,
26
+ },
27
+ });
28
+ /**
29
+ * Wraps an axios instance to add tracing and span tracking
30
+ * @param axios - The axios instance to wrap
31
+ * @param options - Configuration options for HTTP tracing
32
+ * @returns The wrapped axios instance with span tracking
33
+ */
34
+ const traceAxios = (client, { ignoreTraceRoutes = types_1.defaultIgnoreTraceRoutes, traceHeaderKey = types_1.defaultTraceHeaderKey, } = {
35
+ ignoreTraceRoutes: types_1.defaultIgnoreTraceRoutes,
36
+ traceHeaderKey: types_1.defaultTraceHeaderKey,
37
+ }) => {
38
+ const createSpanWrappedRequest = (originalMethod, method) => {
39
+ const { headers: defaultHeaders, ...partialDefaultConfig } = client.defaults;
40
+ const headers = { ...defaultHeaders.common, ...(method && defaultHeaders[method]) };
41
+ const defaultConfig = { ...partialDefaultConfig, headers };
42
+ return async (config) => {
43
+ config = (0, axios_1.mergeConfig)(defaultConfig, config);
44
+ // Determine the actual config and URL
45
+ const url = [config.baseURL, config.url].filter(Boolean).join('');
46
+ // Check if this request should be ignored
47
+ if ((0, utils_1.shouldIgnorePath)(url, ignoreTraceRoutes))
48
+ return originalMethod(config);
49
+ const traceId = storage_1.storage.getStore()?.[storage_1.ContextAttribute.TraceId];
50
+ config = { ...config, headers: { ...config.headers, [traceHeaderKey]: traceId } };
51
+ // Execute the request within a span
52
+ return (0, span_1.startSpan)(`Outgoing HTTP request`, () => originalMethod(config), (options) => {
53
+ if (!options)
54
+ return buildOutgoingHttpPayload(config);
55
+ if (options.error)
56
+ return buildOutgoingHttpPayload(config, (0, axios_1.isAxiosError)(options.error) ? options.error.response : undefined);
57
+ return buildOutgoingHttpPayload(config, options.result);
58
+ });
59
+ };
60
+ };
61
+ const request = client.request.bind(client);
62
+ const tracedRequest = createSpanWrappedRequest(request);
63
+ client.request = tracedRequest;
64
+ ['post', 'put', 'patch'].forEach((method) => {
65
+ const func = createSpanWrappedRequest(request, method);
66
+ client[method] = (url, data, config) => func({ ...config, url, data });
67
+ });
68
+ ['delete', 'get', 'head', 'options'].forEach((method) => {
69
+ const func = createSpanWrappedRequest(request, method);
70
+ client[method] = (url, config) => func({ ...config, url });
71
+ });
72
+ return client;
73
+ };
74
+ exports.traceAxios = traceAxios;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * unnbound-logger
3
+ *
4
+ * A structured logging library built on Pino with TypeScript support.
5
+ * Provides consistent, well-typed logging across different operational contexts.
6
+ */
7
+ export type { LogLevel, LogType, HttpMethod, Log, LogTransaction, SftpLog, HttpLog, SftpPayload, } from './types';
8
+ export type { UnnboundLogger } from './logger';
9
+ export { logger } from './logger';
10
+ export { startSpan } from './span';
11
+ export { traceAxios } from './axios';
12
+ export { traceMiddleware } from './middleware';
@@ -0,0 +1,15 @@
1
+ import pino from 'pino';
2
+ export interface UnnboundLogger extends Omit<pino.Logger, 'trace' | 'debug' | 'error' | 'info' | 'warn'> {
3
+ trace(object: {}, message: string): void;
4
+ trace(message: string): void;
5
+ debug(object: {}, message: string): void;
6
+ debug(message: string): void;
7
+ info(object: {}, message: string): void;
8
+ info(message: string): void;
9
+ warn(object: {}, message: string): void;
10
+ warn(message: string): void;
11
+ error<O extends {
12
+ err: unknown;
13
+ }>(object: O, message: string): void;
14
+ }
15
+ export declare const logger: UnnboundLogger;
package/dist/logger.js ADDED
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.logger = void 0;
7
+ const pino_1 = __importDefault(require("pino"));
8
+ const storage_1 = require("./storage");
9
+ exports.logger = (0, pino_1.default)({
10
+ level: process.env.LOG_LEVEL ?? 'info',
11
+ base: {
12
+ environment: process.env.ENVIRONMENT,
13
+ workflowId: process.env.UNNBOUND_WORKFLOW_ID,
14
+ workflowUrl: process.env.UNNBOUND_WORKFLOW_URL,
15
+ serviceId: process.env.UNNBOUND_SERVICE_ID,
16
+ deploymentId: process.env.UNNBOUND_DEPLOYMENT_ID,
17
+ },
18
+ mixin: () => ({ ...storage_1.storage.getStore() }),
19
+ serializers: {
20
+ req: pino_1.default.stdSerializers.req,
21
+ res: pino_1.default.stdSerializers.res,
22
+ err: pino_1.default.stdSerializers.err,
23
+ },
24
+ // Let CloudWatch handle timestamps
25
+ timestamp: false,
26
+ // Change message field from 'msg' to 'message'
27
+ messageKey: 'message',
28
+ formatters: {
29
+ level: (level) => ({ level }),
30
+ },
31
+ redact: {
32
+ paths: [
33
+ 'http.request.headers.authorization',
34
+ 'http.response.headers.authorization',
35
+ 'http.request.headers.Authorization',
36
+ 'http.response.headers.Authorization',
37
+ 'err.config',
38
+ ],
39
+ remove: true,
40
+ },
41
+ });
42
+ process.on('uncaughtException', (err, origin) => {
43
+ exports.logger.error({ err, origin }, `Uncaught exception.`);
44
+ });
@@ -0,0 +1,3 @@
1
+ import { RequestHandler } from 'express';
2
+ import { HttpOptions } from './types';
3
+ export declare const traceMiddleware: ({ ignoreTraceRoutes, traceHeaderKey, }?: HttpOptions) => RequestHandler;
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.traceMiddleware = void 0;
4
+ const uuid_1 = require("uuid");
5
+ const storage_1 = require("./storage");
6
+ const span_1 = require("./span");
7
+ const types_1 = require("./types");
8
+ const utils_1 = require("./utils");
9
+ const getFullUrl = (req) => {
10
+ const url = req.originalUrl || req.url;
11
+ if (url?.startsWith('http://') || url?.startsWith('https://'))
12
+ return url;
13
+ // Check if we have a workflow URL configured (preferred method)
14
+ if (process.env.UNNBOUND_WORKFLOW_URL) {
15
+ // Use workflow URL as the base URL
16
+ return `${process.env.UNNBOUND_WORKFLOW_URL.replace(/\/$/, '')}${url}`;
17
+ }
18
+ // Fallback to constructing from request info for incoming requests
19
+ const protocol = req.protocol || (req.secure ? 'https' : 'http');
20
+ const host = req.get('host') || req.get('x-forwarded-host') || 'localhost';
21
+ return `${protocol}://${host}${url}`;
22
+ };
23
+ const buildIncomingHttpPayload = (req, res, body) => ({
24
+ type: 'http',
25
+ http: {
26
+ url: getFullUrl(req),
27
+ method: req.method,
28
+ ip: (0, utils_1.normalizeIp)(req.ip),
29
+ incoming: true,
30
+ request: {
31
+ headers: req.headers,
32
+ body: (0, utils_1.safeJsonParse)(req.body),
33
+ },
34
+ response: res
35
+ ? {
36
+ headers: res?.headers,
37
+ status: res.statusCode,
38
+ body: (0, utils_1.safeJsonParse)(body),
39
+ }
40
+ : undefined,
41
+ },
42
+ });
43
+ const traceMiddleware = ({ ignoreTraceRoutes = types_1.defaultIgnoreTraceRoutes, traceHeaderKey = types_1.defaultTraceHeaderKey, } = {
44
+ ignoreTraceRoutes: types_1.defaultIgnoreTraceRoutes,
45
+ traceHeaderKey: types_1.defaultTraceHeaderKey,
46
+ }) => async (req, res, next) => {
47
+ if ((0, utils_1.shouldIgnorePath)(req.path, ignoreTraceRoutes))
48
+ return next();
49
+ const traceId = req.header(traceHeaderKey) || (0, uuid_1.v4)();
50
+ res.setHeader(traceHeaderKey, traceId);
51
+ return await storage_1.storage.run({ [storage_1.ContextAttribute.TraceId]: traceId }, async () => {
52
+ return await (0, span_1.startSpan)('Incoming HTTP request', async () => {
53
+ return new Promise((resolve) => {
54
+ // Capture response body for logging
55
+ const send = res.send.bind(res);
56
+ res.send = (body) => {
57
+ res.locals.body = body;
58
+ return send(body);
59
+ };
60
+ res.on('finish', () => resolve());
61
+ return next();
62
+ });
63
+ }, (o) => {
64
+ return buildIncomingHttpPayload(req, o
65
+ ? { statusCode: res.statusCode, headers: res.getHeaders() }
66
+ : undefined, res.locals.body);
67
+ });
68
+ });
69
+ };
70
+ exports.traceMiddleware = traceMiddleware;
package/dist/span.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ type LogPayloadGetterOptions<T> = {
2
+ error: unknown;
3
+ result?: never;
4
+ } | {
5
+ error?: never;
6
+ result: T;
7
+ };
8
+ type LogPayloadGetter<T> = object | ((o?: LogPayloadGetterOptions<T>) => object);
9
+ /**
10
+ * Starts a span that tracks the duration of a callback
11
+ * @param spanName - The span name to use for logging
12
+ * @param callback - The async callback to execute
13
+ * @returns The result of the callback
14
+ */
15
+ export declare const startSpan: <T>(spanName: string, callback: () => Promise<T>, getter?: LogPayloadGetter<T>) => Promise<T>;
16
+ export {};
package/dist/span.js ADDED
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.startSpan = void 0;
4
+ const uuid_1 = require("uuid");
5
+ const storage_1 = require("./storage");
6
+ const logger_1 = require("./logger");
7
+ /**
8
+ * Starts a span that tracks the duration of a callback
9
+ * @param spanName - The span name to use for logging
10
+ * @param callback - The async callback to execute
11
+ * @returns The result of the callback
12
+ */
13
+ const startSpan = async (spanName, callback, getter) => {
14
+ const spanId = (0, uuid_1.v4)();
15
+ const start = performance.now();
16
+ const previous = storage_1.storage.getStore();
17
+ return storage_1.storage.run({
18
+ ...previous,
19
+ [storage_1.ContextAttribute.SpanId]: previous?.[storage_1.ContextAttribute.SpanId]
20
+ ? `${spanId} ${previous?.[storage_1.ContextAttribute.SpanId]}`
21
+ : spanId,
22
+ }, async () => {
23
+ logger_1.logger.info({ ...getLogPayload(getter) }, `${spanName} started.`);
24
+ try {
25
+ const result = await callback();
26
+ logger_1.logger.info({ ...getLogPayload(getter, { result }), duration: getDuration(start) }, `${spanName} completed.`);
27
+ return result;
28
+ }
29
+ catch (error) {
30
+ logger_1.logger.error({ ...getLogPayload(getter, { error }), err: error, duration: getDuration(start) }, `${spanName} failed.`);
31
+ throw error;
32
+ }
33
+ });
34
+ };
35
+ exports.startSpan = startSpan;
36
+ const getLogPayload = (getter, o) => {
37
+ if (typeof getter !== 'function')
38
+ return getter;
39
+ return getter(o);
40
+ };
41
+ const getDuration = (start) => Math.round(performance.now() - start);
@@ -0,0 +1,10 @@
1
+ import { AsyncLocalStorage } from 'async_hooks';
2
+ export declare enum ContextAttribute {
3
+ TraceId = "traceId",
4
+ SpanId = "spanId"
5
+ }
6
+ export interface Context {
7
+ [ContextAttribute.TraceId]?: string;
8
+ [ContextAttribute.SpanId]?: string;
9
+ }
10
+ export declare const storage: AsyncLocalStorage<Context>;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.storage = exports.ContextAttribute = void 0;
4
+ const async_hooks_1 = require("async_hooks");
5
+ var ContextAttribute;
6
+ (function (ContextAttribute) {
7
+ ContextAttribute["TraceId"] = "traceId";
8
+ ContextAttribute["SpanId"] = "spanId";
9
+ })(ContextAttribute || (exports.ContextAttribute = ContextAttribute = {}));
10
+ exports.storage = new async_hooks_1.AsyncLocalStorage();
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Type definitions for structured logging library
3
+ */
4
+ /**
5
+ * Available log levels
6
+ */
7
+ export type LogLevel = 'info' | 'debug' | 'error' | 'warn';
8
+ /**
9
+ * Available log types
10
+ */
11
+ export type LogType = 'general' | 'http' | 'sftp' | 'dbQueryTransaction';
12
+ /**
13
+ * HTTP methods supported for HTTP logging
14
+ */
15
+ export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS' | 'HEAD';
16
+ export interface Log<T extends LogType = 'general'> {
17
+ level: LogLevel;
18
+ message: string;
19
+ traceId: string;
20
+ spanId?: string;
21
+ type: T;
22
+ serviceId: string;
23
+ deploymentId: string;
24
+ workflowId: string;
25
+ err?: unknown;
26
+ }
27
+ export interface LogTransaction<T extends LogType> extends Log<T> {
28
+ duration?: number;
29
+ }
30
+ export interface HttpLog extends LogTransaction<'http'> {
31
+ http: {
32
+ url: string;
33
+ method: string;
34
+ ip?: string;
35
+ request: {
36
+ headers: Record<string, string>;
37
+ body?: unknown;
38
+ };
39
+ response?: {
40
+ headers: Record<string, string>;
41
+ status: number;
42
+ body?: unknown;
43
+ };
44
+ };
45
+ }
46
+ export type SftpOperation = 'connect' | 'upload' | 'download' | 'list' | 'delete' | 'rename' | 'stat' | 'exists' | 'realPath' | 'get' | 'put' | 'cwd' | 'mkdir' | 'rmdir' | 'chmod' | 'append' | 'uploadDir' | 'downloadDir' | 'end';
47
+ export interface SftpPayload {
48
+ host: string;
49
+ operation: SftpOperation;
50
+ path?: string;
51
+ bytes?: number;
52
+ destinationPath?: string;
53
+ files?: number;
54
+ }
55
+ export interface SftpLog extends LogTransaction<'sftp'> {
56
+ sftp: SftpPayload;
57
+ }
58
+ export interface HttpOptions {
59
+ ignoreTraceRoutes?: string[];
60
+ traceHeaderKey?: string;
61
+ }
62
+ export declare const defaultIgnoreTraceRoutes: string[];
63
+ export declare const defaultTraceHeaderKey = "x-unnbound-trace-id";
package/dist/types.js ADDED
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ /**
3
+ * Type definitions for structured logging library
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.defaultTraceHeaderKey = exports.defaultIgnoreTraceRoutes = void 0;
7
+ exports.defaultIgnoreTraceRoutes = ['/health', '/healthcheck'];
8
+ exports.defaultTraceHeaderKey = 'x-unnbound-trace-id';
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Checks if a path matches any of the ignore patterns
3
+ * @param path - The path to check
4
+ * @param patterns - Array of glob patterns to match against
5
+ * @returns boolean indicating if the path should be ignored
6
+ */
7
+ export declare const shouldIgnorePath: (path: string, patterns: string[]) => boolean;
8
+ /**
9
+ * Safely parses JSON strings, returning the original data if parsing fails or if it's not a string.
10
+ * @param data The data to potentially parse as JSON.
11
+ * @returns Parsed JSON object or the original data.
12
+ */
13
+ export declare function safeJsonParse(data: any): any;
14
+ /**
15
+ * Normalizes IP addresses by removing IPv6 mapping prefix for IPv4 addresses.
16
+ * @param ip The IP address to normalize.
17
+ * @returns Normalized IP address string.
18
+ */
19
+ export declare function normalizeIp(ip: string | undefined): string | undefined;
package/dist/utils.js ADDED
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.shouldIgnorePath = void 0;
4
+ exports.safeJsonParse = safeJsonParse;
5
+ exports.normalizeIp = normalizeIp;
6
+ /**
7
+ * Checks if a path matches any of the ignore patterns
8
+ * @param path - The path to check
9
+ * @param patterns - Array of glob patterns to match against
10
+ * @returns boolean indicating if the path should be ignored
11
+ */
12
+ const shouldIgnorePath = (path, patterns) => {
13
+ return patterns.some((pattern) => {
14
+ // Convert glob pattern to regex
15
+ const regexPattern = pattern
16
+ .replace(/\./g, '\\.') // Escape dots
17
+ .replace(/\*/g, '.*') // Convert * to .*
18
+ .replace(/\?/g, '.'); // Convert ? to .
19
+ const regex = new RegExp(`^${regexPattern}$`);
20
+ return regex.test(path);
21
+ });
22
+ };
23
+ exports.shouldIgnorePath = shouldIgnorePath;
24
+ /**
25
+ * Safely parses JSON strings, returning the original data if parsing fails or if it's not a string.
26
+ * @param data The data to potentially parse as JSON.
27
+ * @returns Parsed JSON object or the original data.
28
+ */
29
+ function safeJsonParse(data) {
30
+ if (typeof data === 'string') {
31
+ try {
32
+ return JSON.parse(data);
33
+ }
34
+ catch {
35
+ return data;
36
+ }
37
+ }
38
+ return data;
39
+ }
40
+ /**
41
+ * Normalizes IP addresses by removing IPv6 mapping prefix for IPv4 addresses.
42
+ * @param ip The IP address to normalize.
43
+ * @returns Normalized IP address string.
44
+ */
45
+ function normalizeIp(ip) {
46
+ if (!ip)
47
+ return ip;
48
+ // Remove IPv4-mapped IPv6 prefix (::ffff:) to get clean IPv4 address
49
+ if (ip.startsWith('::ffff:')) {
50
+ return ip.substring(7);
51
+ }
52
+ return ip;
53
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "unnbound-logger-sdk",
3
3
  "description": "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.",
4
- "version": "3.0.0",
4
+ "version": "3.0.2",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "keywords": [
@@ -50,7 +50,7 @@
50
50
  }
51
51
  },
52
52
  "files": [
53
- "dist/src/**/*",
53
+ "dist/**/*",
54
54
  "README.md",
55
55
  "LICENSE"
56
56
  ],
@@ -63,6 +63,7 @@
63
63
  "test": "jest",
64
64
  "test:coverage": "jest --coverage",
65
65
  "test:watch": "jest --watch",
66
+ "typecheck": "tsc -noEmit",
66
67
  "lint": "eslint --cache --cache-location ./node_modules/.cache/eslint .",
67
68
  "lint:fix": "pnpm lint --fix",
68
69
  "format": "prettier --write .",