unnbound-logger-sdk 3.0.0 → 3.0.1

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;
package/dist/http.d.ts ADDED
File without changes
package/dist/http.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";
@@ -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/sftp.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ import { SftpPayload } from './types';
2
+ /**
3
+ * Builds a SFTP payload
4
+ * @param payload - SFTP payload
5
+ * @returns The SFTP payload
6
+ */
7
+ export declare const buildSftpPayload: (payload: SftpPayload) => {
8
+ type: string;
9
+ sftp: SftpPayload;
10
+ };
package/dist/sftp.js ADDED
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildSftpPayload = void 0;
4
+ /**
5
+ * Builds a SFTP payload
6
+ * @param payload - SFTP payload
7
+ * @returns The SFTP payload
8
+ */
9
+ const buildSftpPayload = (payload) => ({
10
+ type: 'sftp',
11
+ sftp: payload,
12
+ });
13
+ exports.buildSftpPayload = buildSftpPayload;
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,114 @@
1
+ /**
2
+ * Core logger implementation
3
+ */
4
+ import pino from 'pino';
5
+ import { LogLevel, LoggerOptions, GeneralLogOptions, HttpRequestLogOptions, HttpResponseLogOptions, DbQueryTransactionLogOptions, Log, HttpRequestLog, HttpResponseLog, DbQueryTransactionLog } from './types';
6
+ import { Request, Response, NextFunction } from 'express';
7
+ import { InternalAxiosRequestConfig } from 'axios';
8
+ declare module 'axios' {
9
+ interface InternalAxiosRequestConfig {
10
+ metadata?: {
11
+ startTime: number;
12
+ requestId?: string;
13
+ };
14
+ }
15
+ }
16
+ export declare const logger: pino.Logger;
17
+ /**
18
+ * UnnboundLogger provides typed, structured logging using Pino
19
+ */
20
+ export declare class UnnboundLogger {
21
+ private logger;
22
+ private workflowId;
23
+ private workflowUrl;
24
+ private serviceId;
25
+ private deploymentId;
26
+ private traceHeaderKey;
27
+ private ignoreTraceRoutes;
28
+ private ignoreAxiosTraceRoutes;
29
+ /**
30
+ * Creates a new UnnboundLogger instance
31
+ * @param options - Configuration options for the logger
32
+ */
33
+ constructor(options?: LoggerOptions);
34
+ /**
35
+ * Checks if a path matches any of the ignore patterns
36
+ * @param path - The path to check
37
+ * @param patterns - Array of glob patterns to match against
38
+ * @returns boolean indicating if the path should be ignored
39
+ */
40
+ private shouldIgnorePath;
41
+ /**
42
+ * Logs a general message
43
+ * @param level - Log level
44
+ * @param message - Log message
45
+ * @param options - Additional logging options
46
+ */
47
+ log(level: LogLevel, message: string | Error | Record<string, unknown>, options?: GeneralLogOptions): Log;
48
+ /**
49
+ * Logs an error message
50
+ * @param message - Error message or object
51
+ * @param options - Additional logging options
52
+ */
53
+ error(message: string | Error | Record<string, unknown>, options?: GeneralLogOptions): Log;
54
+ /**
55
+ * Logs a warning message
56
+ * @param message - Warning message
57
+ * @param options - Additional logging options
58
+ */
59
+ warn(message: string | Error | Record<string, unknown>, options?: GeneralLogOptions): Log;
60
+ /**
61
+ * Logs an info message
62
+ * @param message - Info message
63
+ * @param options - Additional logging options
64
+ */
65
+ info(message: string | Error | Record<string, unknown>, options?: GeneralLogOptions): Log;
66
+ /**
67
+ * Logs a debug message
68
+ * @param message - Debug message
69
+ * @param options - Additional logging options
70
+ */
71
+ debug(message: string | Error | Record<string, unknown>, options?: GeneralLogOptions): Log;
72
+ /**
73
+ * Constructs the full URL from request information
74
+ * @param req - Express request object
75
+ * @returns Full URL string
76
+ */
77
+ private constructFullUrl;
78
+ /**
79
+ * Logs an HTTP request
80
+ * @param req - Express request object
81
+ * @param options - Additional logging options
82
+ * @returns The request ID for correlating with the response
83
+ */
84
+ httpRequest(req: Request, options?: HttpRequestLogOptions): HttpRequestLog;
85
+ /**
86
+ * Logs an HTTP response
87
+ * @param res - Express response object
88
+ * @param req - Express request object
89
+ * @param options - Additional logging options
90
+ */
91
+ httpResponse(res: Response, req: Request, options?: HttpResponseLogOptions): HttpResponseLog;
92
+ /**
93
+ * Logs a database query transaction
94
+ * @param query - Database query details
95
+ * @param options - Additional logging options
96
+ */
97
+ dbQueryTransaction(query: {
98
+ instance: string;
99
+ vendor: 'postgres' | 'mysql' | 'mssql' | 'mongodb';
100
+ query?: string;
101
+ status: 'success' | 'failure';
102
+ rowsReturned?: number;
103
+ rowsAffected?: number;
104
+ }, options?: DbQueryTransactionLogOptions): DbQueryTransactionLog;
105
+ traceMiddleware: (req: Request, res: Response, next: NextFunction) => void;
106
+ axiosTraceMiddleware: {
107
+ onFulfilled: (config: InternalAxiosRequestConfig) => InternalAxiosRequestConfig;
108
+ onRejected: (error: any) => any;
109
+ };
110
+ axiosResponseInterceptor: {
111
+ onFulfilled: (response: any) => any;
112
+ onRejected: (error: any) => any;
113
+ };
114
+ }