@saga-bus/middleware-logging 1.0.0

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Dean Foran
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,50 @@
1
+ # @saga-bus/middleware-logging
2
+
3
+ Structured logging middleware for saga-bus.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pnpm add @saga-bus/middleware-logging
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```typescript
14
+ import { createLoggingMiddleware } from "@saga-bus/middleware-logging";
15
+ import { createBus } from "@saga-bus/core";
16
+
17
+ const loggingMiddleware = createLoggingMiddleware({
18
+ logger: console,
19
+ level: "info",
20
+ });
21
+
22
+ const bus = createBus({
23
+ middleware: [loggingMiddleware],
24
+ sagas: [...],
25
+ transport,
26
+ });
27
+ ```
28
+
29
+ ## Log Events
30
+
31
+ | Event | Level | Description |
32
+ |-------|-------|-------------|
33
+ | `saga.message.received` | info | Message received for processing |
34
+ | `saga.handler.start` | debug | Handler execution started |
35
+ | `saga.handler.success` | info | Handler completed successfully |
36
+ | `saga.handler.error` | error | Handler threw an error |
37
+ | `saga.state.created` | info | New saga instance created |
38
+ | `saga.state.completed` | info | Saga marked as complete |
39
+
40
+ ## Configuration
41
+
42
+ | Option | Type | Default | Description |
43
+ |--------|------|---------|-------------|
44
+ | `logger` | `Logger` | `console` | Logger instance |
45
+ | `level` | `string` | `"info"` | Minimum log level |
46
+ | `includeState` | `boolean` | `false` | Include state in logs |
47
+
48
+ ## License
49
+
50
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,143 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ createLoggingMiddleware: () => createLoggingMiddleware
24
+ });
25
+ module.exports = __toCommonJS(index_exports);
26
+
27
+ // src/createLoggingMiddleware.ts
28
+ var LOG_LEVEL_PRIORITY = {
29
+ debug: 0,
30
+ info: 1,
31
+ warn: 2,
32
+ error: 3
33
+ };
34
+ var defaultLogger = {
35
+ debug: (message, meta) => console.debug(`[saga-bus] ${message}`, meta ?? ""),
36
+ info: (message, meta) => console.info(`[saga-bus] ${message}`, meta ?? ""),
37
+ warn: (message, meta) => console.warn(`[saga-bus] ${message}`, meta ?? ""),
38
+ error: (message, meta) => console.error(`[saga-bus] ${message}`, meta ?? "")
39
+ };
40
+ function createLoggingMiddleware(options = {}) {
41
+ const {
42
+ logger = defaultLogger,
43
+ level = "info",
44
+ logPayload = false,
45
+ logState = false,
46
+ filter,
47
+ enrichMeta
48
+ } = options;
49
+ const minPriority = LOG_LEVEL_PRIORITY[level];
50
+ function log(eventLevel, eventType, message, meta) {
51
+ if (LOG_LEVEL_PRIORITY[eventLevel] < minPriority) {
52
+ return;
53
+ }
54
+ if (filter && !filter(eventType, meta)) {
55
+ return;
56
+ }
57
+ const enrichedMeta = enrichMeta ? enrichMeta(meta) : meta;
58
+ const finalMeta = { ...enrichedMeta, event: eventType };
59
+ switch (eventLevel) {
60
+ case "debug":
61
+ logger.debug(message, finalMeta);
62
+ break;
63
+ case "info":
64
+ logger.info(message, finalMeta);
65
+ break;
66
+ case "warn":
67
+ logger.warn(message, finalMeta);
68
+ break;
69
+ case "error":
70
+ logger.error(message, finalMeta);
71
+ break;
72
+ }
73
+ }
74
+ function baseMeta(ctx) {
75
+ const meta = {
76
+ sagaName: ctx.sagaName,
77
+ correlationId: ctx.correlationId,
78
+ messageId: ctx.envelope.id,
79
+ messageType: ctx.envelope.type
80
+ };
81
+ if (ctx.sagaId) {
82
+ meta.sagaId = ctx.sagaId;
83
+ }
84
+ if (logPayload) {
85
+ meta.payload = ctx.envelope.payload;
86
+ }
87
+ return meta;
88
+ }
89
+ return async (ctx, next) => {
90
+ const startTime = Date.now();
91
+ log("debug", "saga.message.received", "Message received", {
92
+ ...baseMeta(ctx),
93
+ headers: ctx.envelope.headers
94
+ });
95
+ log("debug", "saga.handler.start", "Handler starting", baseMeta(ctx));
96
+ try {
97
+ await next();
98
+ const duration = Date.now() - startTime;
99
+ const isNew = ctx.preState === void 0 && ctx.postState !== void 0;
100
+ const isCompleted = ctx.postState?.metadata?.isCompleted === true;
101
+ const wasAlreadyCompleted = ctx.preState?.metadata?.isCompleted === true;
102
+ const resultMeta = {
103
+ ...baseMeta(ctx),
104
+ durationMs: duration
105
+ };
106
+ if (ctx.sagaId) {
107
+ resultMeta.sagaId = ctx.sagaId;
108
+ }
109
+ if (logState && ctx.postState) {
110
+ resultMeta.state = ctx.postState;
111
+ }
112
+ if (ctx.postState) {
113
+ resultMeta.version = ctx.postState.metadata.version;
114
+ }
115
+ if (isNew) {
116
+ log("info", "saga.state.created", "Saga instance created", resultMeta);
117
+ } else if (isCompleted && !wasAlreadyCompleted) {
118
+ log("info", "saga.state.completed", "Saga completed", resultMeta);
119
+ } else if (ctx.postState) {
120
+ log("debug", "saga.state.updated", "Saga state updated", resultMeta);
121
+ }
122
+ log("debug", "saga.handler.success", "Handler completed successfully", {
123
+ ...baseMeta(ctx),
124
+ durationMs: duration
125
+ });
126
+ } catch (error) {
127
+ const duration = Date.now() - startTime;
128
+ log("error", "saga.handler.error", "Handler failed", {
129
+ ...baseMeta(ctx),
130
+ durationMs: duration,
131
+ error: error instanceof Error ? error.message : String(error),
132
+ errorType: error instanceof Error ? error.name : "UnknownError",
133
+ stack: error instanceof Error ? error.stack : void 0
134
+ });
135
+ throw error;
136
+ }
137
+ };
138
+ }
139
+ // Annotate the CommonJS export names for ESM import in node:
140
+ 0 && (module.exports = {
141
+ createLoggingMiddleware
142
+ });
143
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/createLoggingMiddleware.ts"],"sourcesContent":["export { createLoggingMiddleware } from \"./createLoggingMiddleware.js\";\nexport type {\n LoggingMiddlewareOptions,\n LogLevel,\n LogEventType,\n} from \"./types.js\";\n","import type { SagaMiddleware, SagaPipelineContext, Logger } from \"@saga-bus/core\";\nimport type { LoggingMiddlewareOptions, LogLevel, LogEventType } from \"./types.js\";\n\n/**\n * Log level priorities for filtering.\n */\nconst LOG_LEVEL_PRIORITY: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n};\n\n/**\n * Default console-based logger.\n */\nconst defaultLogger: Logger = {\n debug: (message, meta) => console.debug(`[saga-bus] ${message}`, meta ?? \"\"),\n info: (message, meta) => console.info(`[saga-bus] ${message}`, meta ?? \"\"),\n warn: (message, meta) => console.warn(`[saga-bus] ${message}`, meta ?? \"\"),\n error: (message, meta) => console.error(`[saga-bus] ${message}`, meta ?? \"\"),\n};\n\n/**\n * Create a logging middleware for saga execution.\n *\n * @example\n * ```typescript\n * const loggingMiddleware = createLoggingMiddleware({\n * level: \"debug\",\n * logPayload: true,\n * });\n *\n * const bus = createBus({\n * transport,\n * sagas: [...],\n * middleware: [loggingMiddleware],\n * });\n * ```\n */\nexport function createLoggingMiddleware(\n options: LoggingMiddlewareOptions = {}\n): SagaMiddleware {\n const {\n logger = defaultLogger,\n level = \"info\",\n logPayload = false,\n logState = false,\n filter,\n enrichMeta,\n } = options;\n\n const minPriority = LOG_LEVEL_PRIORITY[level];\n\n /**\n * Log an event if it meets the level threshold.\n */\n function log(\n eventLevel: LogLevel,\n eventType: LogEventType,\n message: string,\n meta: Record<string, unknown>\n ): void {\n if (LOG_LEVEL_PRIORITY[eventLevel] < minPriority) {\n return;\n }\n\n if (filter && !filter(eventType, meta)) {\n return;\n }\n\n const enrichedMeta = enrichMeta ? enrichMeta(meta) : meta;\n const finalMeta = { ...enrichedMeta, event: eventType };\n\n switch (eventLevel) {\n case \"debug\":\n logger.debug(message, finalMeta);\n break;\n case \"info\":\n logger.info(message, finalMeta);\n break;\n case \"warn\":\n logger.warn(message, finalMeta);\n break;\n case \"error\":\n logger.error(message, finalMeta);\n break;\n }\n }\n\n /**\n * Build base metadata from pipeline context.\n */\n function baseMeta(ctx: SagaPipelineContext): Record<string, unknown> {\n const meta: Record<string, unknown> = {\n sagaName: ctx.sagaName,\n correlationId: ctx.correlationId,\n messageId: ctx.envelope.id,\n messageType: ctx.envelope.type,\n };\n\n if (ctx.sagaId) {\n meta.sagaId = ctx.sagaId;\n }\n\n if (logPayload) {\n meta.payload = ctx.envelope.payload;\n }\n\n return meta;\n }\n\n return async (ctx: SagaPipelineContext, next: () => Promise<void>) => {\n const startTime = Date.now();\n\n // Log message received\n log(\"debug\", \"saga.message.received\", \"Message received\", {\n ...baseMeta(ctx),\n headers: ctx.envelope.headers,\n });\n\n // Log handler start\n log(\"debug\", \"saga.handler.start\", \"Handler starting\", baseMeta(ctx));\n\n try {\n await next();\n\n const duration = Date.now() - startTime;\n\n // Determine what happened\n const isNew = ctx.preState === undefined && ctx.postState !== undefined;\n const isCompleted = ctx.postState?.metadata?.isCompleted === true;\n const wasAlreadyCompleted = ctx.preState?.metadata?.isCompleted === true;\n\n // Build result metadata\n const resultMeta: Record<string, unknown> = {\n ...baseMeta(ctx),\n durationMs: duration,\n };\n\n if (ctx.sagaId) {\n resultMeta.sagaId = ctx.sagaId;\n }\n\n if (logState && ctx.postState) {\n resultMeta.state = ctx.postState;\n }\n\n if (ctx.postState) {\n resultMeta.version = ctx.postState.metadata.version;\n }\n\n // Log appropriate event\n if (isNew) {\n log(\"info\", \"saga.state.created\", \"Saga instance created\", resultMeta);\n } else if (isCompleted && !wasAlreadyCompleted) {\n log(\"info\", \"saga.state.completed\", \"Saga completed\", resultMeta);\n } else if (ctx.postState) {\n log(\"debug\", \"saga.state.updated\", \"Saga state updated\", resultMeta);\n }\n\n // Log handler success\n log(\"debug\", \"saga.handler.success\", \"Handler completed successfully\", {\n ...baseMeta(ctx),\n durationMs: duration,\n });\n } catch (error) {\n const duration = Date.now() - startTime;\n\n // Log handler error\n log(\"error\", \"saga.handler.error\", \"Handler failed\", {\n ...baseMeta(ctx),\n durationMs: duration,\n error: error instanceof Error ? error.message : String(error),\n errorType: error instanceof Error ? error.name : \"UnknownError\",\n stack: error instanceof Error ? error.stack : undefined,\n });\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SAAS,sBAAsB,sBAAsB,UAAU;AAAA,MACrE;AAGA,UAAI,SAAS,wBAAwB,kCAAkC;AAAA,QACrE,GAAG,SAAS,GAAG;AAAA,QACf,YAAY;AAAA,MACd,CAAC;AAAA,IACH,SAAS,OAAO;AACd,YAAM,WAAW,KAAK,IAAI,IAAI;AAG9B,UAAI,SAAS,sBAAsB,kBAAkB;AAAA,QACnD,GAAG,SAAS,GAAG;AAAA,QACf,YAAY;AAAA,QACZ,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,QAC5D,WAAW,iBAAiB,QAAQ,MAAM,OAAO;AAAA,QACjD,OAAO,iBAAiB,QAAQ,MAAM,QAAQ;AAAA,MAChD,CAAC;AAGD,YAAM;AAAA,IACR;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,61 @@
1
+ import { Logger, SagaMiddleware } from '@saga-bus/core';
2
+
3
+ /**
4
+ * Log level for filtering.
5
+ */
6
+ type LogLevel = "debug" | "info" | "warn" | "error";
7
+ /**
8
+ * Log event types emitted by the middleware.
9
+ */
10
+ type LogEventType = "saga.message.received" | "saga.handler.start" | "saga.handler.success" | "saga.handler.error" | "saga.state.created" | "saga.state.updated" | "saga.state.completed";
11
+ /**
12
+ * Options for the logging middleware.
13
+ */
14
+ interface LoggingMiddlewareOptions {
15
+ /**
16
+ * Logger instance to use. Defaults to console-based logger.
17
+ */
18
+ logger?: Logger;
19
+ /**
20
+ * Minimum log level. Events below this level are not logged.
21
+ * Default: "info"
22
+ */
23
+ level?: LogLevel;
24
+ /**
25
+ * Whether to log message payload. Default: false (for security/privacy).
26
+ */
27
+ logPayload?: boolean;
28
+ /**
29
+ * Whether to log full state. Default: false (can be large).
30
+ */
31
+ logState?: boolean;
32
+ /**
33
+ * Custom event filter. Return false to skip logging an event.
34
+ */
35
+ filter?: (eventType: LogEventType, meta: Record<string, unknown>) => boolean;
36
+ /**
37
+ * Custom metadata enricher. Add extra fields to all log events.
38
+ */
39
+ enrichMeta?: (meta: Record<string, unknown>) => Record<string, unknown>;
40
+ }
41
+
42
+ /**
43
+ * Create a logging middleware for saga execution.
44
+ *
45
+ * @example
46
+ * ```typescript
47
+ * const loggingMiddleware = createLoggingMiddleware({
48
+ * level: "debug",
49
+ * logPayload: true,
50
+ * });
51
+ *
52
+ * const bus = createBus({
53
+ * transport,
54
+ * sagas: [...],
55
+ * middleware: [loggingMiddleware],
56
+ * });
57
+ * ```
58
+ */
59
+ declare function createLoggingMiddleware(options?: LoggingMiddlewareOptions): SagaMiddleware;
60
+
61
+ export { type LogEventType, type LogLevel, type LoggingMiddlewareOptions, createLoggingMiddleware };
@@ -0,0 +1,61 @@
1
+ import { Logger, SagaMiddleware } from '@saga-bus/core';
2
+
3
+ /**
4
+ * Log level for filtering.
5
+ */
6
+ type LogLevel = "debug" | "info" | "warn" | "error";
7
+ /**
8
+ * Log event types emitted by the middleware.
9
+ */
10
+ type LogEventType = "saga.message.received" | "saga.handler.start" | "saga.handler.success" | "saga.handler.error" | "saga.state.created" | "saga.state.updated" | "saga.state.completed";
11
+ /**
12
+ * Options for the logging middleware.
13
+ */
14
+ interface LoggingMiddlewareOptions {
15
+ /**
16
+ * Logger instance to use. Defaults to console-based logger.
17
+ */
18
+ logger?: Logger;
19
+ /**
20
+ * Minimum log level. Events below this level are not logged.
21
+ * Default: "info"
22
+ */
23
+ level?: LogLevel;
24
+ /**
25
+ * Whether to log message payload. Default: false (for security/privacy).
26
+ */
27
+ logPayload?: boolean;
28
+ /**
29
+ * Whether to log full state. Default: false (can be large).
30
+ */
31
+ logState?: boolean;
32
+ /**
33
+ * Custom event filter. Return false to skip logging an event.
34
+ */
35
+ filter?: (eventType: LogEventType, meta: Record<string, unknown>) => boolean;
36
+ /**
37
+ * Custom metadata enricher. Add extra fields to all log events.
38
+ */
39
+ enrichMeta?: (meta: Record<string, unknown>) => Record<string, unknown>;
40
+ }
41
+
42
+ /**
43
+ * Create a logging middleware for saga execution.
44
+ *
45
+ * @example
46
+ * ```typescript
47
+ * const loggingMiddleware = createLoggingMiddleware({
48
+ * level: "debug",
49
+ * logPayload: true,
50
+ * });
51
+ *
52
+ * const bus = createBus({
53
+ * transport,
54
+ * sagas: [...],
55
+ * middleware: [loggingMiddleware],
56
+ * });
57
+ * ```
58
+ */
59
+ declare function createLoggingMiddleware(options?: LoggingMiddlewareOptions): SagaMiddleware;
60
+
61
+ export { type LogEventType, type LogLevel, type LoggingMiddlewareOptions, createLoggingMiddleware };
package/dist/index.js ADDED
@@ -0,0 +1,116 @@
1
+ // src/createLoggingMiddleware.ts
2
+ var LOG_LEVEL_PRIORITY = {
3
+ debug: 0,
4
+ info: 1,
5
+ warn: 2,
6
+ error: 3
7
+ };
8
+ var defaultLogger = {
9
+ debug: (message, meta) => console.debug(`[saga-bus] ${message}`, meta ?? ""),
10
+ info: (message, meta) => console.info(`[saga-bus] ${message}`, meta ?? ""),
11
+ warn: (message, meta) => console.warn(`[saga-bus] ${message}`, meta ?? ""),
12
+ error: (message, meta) => console.error(`[saga-bus] ${message}`, meta ?? "")
13
+ };
14
+ function createLoggingMiddleware(options = {}) {
15
+ const {
16
+ logger = defaultLogger,
17
+ level = "info",
18
+ logPayload = false,
19
+ logState = false,
20
+ filter,
21
+ enrichMeta
22
+ } = options;
23
+ const minPriority = LOG_LEVEL_PRIORITY[level];
24
+ function log(eventLevel, eventType, message, meta) {
25
+ if (LOG_LEVEL_PRIORITY[eventLevel] < minPriority) {
26
+ return;
27
+ }
28
+ if (filter && !filter(eventType, meta)) {
29
+ return;
30
+ }
31
+ const enrichedMeta = enrichMeta ? enrichMeta(meta) : meta;
32
+ const finalMeta = { ...enrichedMeta, event: eventType };
33
+ switch (eventLevel) {
34
+ case "debug":
35
+ logger.debug(message, finalMeta);
36
+ break;
37
+ case "info":
38
+ logger.info(message, finalMeta);
39
+ break;
40
+ case "warn":
41
+ logger.warn(message, finalMeta);
42
+ break;
43
+ case "error":
44
+ logger.error(message, finalMeta);
45
+ break;
46
+ }
47
+ }
48
+ function baseMeta(ctx) {
49
+ const meta = {
50
+ sagaName: ctx.sagaName,
51
+ correlationId: ctx.correlationId,
52
+ messageId: ctx.envelope.id,
53
+ messageType: ctx.envelope.type
54
+ };
55
+ if (ctx.sagaId) {
56
+ meta.sagaId = ctx.sagaId;
57
+ }
58
+ if (logPayload) {
59
+ meta.payload = ctx.envelope.payload;
60
+ }
61
+ return meta;
62
+ }
63
+ return async (ctx, next) => {
64
+ const startTime = Date.now();
65
+ log("debug", "saga.message.received", "Message received", {
66
+ ...baseMeta(ctx),
67
+ headers: ctx.envelope.headers
68
+ });
69
+ log("debug", "saga.handler.start", "Handler starting", baseMeta(ctx));
70
+ try {
71
+ await next();
72
+ const duration = Date.now() - startTime;
73
+ const isNew = ctx.preState === void 0 && ctx.postState !== void 0;
74
+ const isCompleted = ctx.postState?.metadata?.isCompleted === true;
75
+ const wasAlreadyCompleted = ctx.preState?.metadata?.isCompleted === true;
76
+ const resultMeta = {
77
+ ...baseMeta(ctx),
78
+ durationMs: duration
79
+ };
80
+ if (ctx.sagaId) {
81
+ resultMeta.sagaId = ctx.sagaId;
82
+ }
83
+ if (logState && ctx.postState) {
84
+ resultMeta.state = ctx.postState;
85
+ }
86
+ if (ctx.postState) {
87
+ resultMeta.version = ctx.postState.metadata.version;
88
+ }
89
+ if (isNew) {
90
+ log("info", "saga.state.created", "Saga instance created", resultMeta);
91
+ } else if (isCompleted && !wasAlreadyCompleted) {
92
+ log("info", "saga.state.completed", "Saga completed", resultMeta);
93
+ } else if (ctx.postState) {
94
+ log("debug", "saga.state.updated", "Saga state updated", resultMeta);
95
+ }
96
+ log("debug", "saga.handler.success", "Handler completed successfully", {
97
+ ...baseMeta(ctx),
98
+ durationMs: duration
99
+ });
100
+ } catch (error) {
101
+ const duration = Date.now() - startTime;
102
+ log("error", "saga.handler.error", "Handler failed", {
103
+ ...baseMeta(ctx),
104
+ durationMs: duration,
105
+ error: error instanceof Error ? error.message : String(error),
106
+ errorType: error instanceof Error ? error.name : "UnknownError",
107
+ stack: error instanceof Error ? error.stack : void 0
108
+ });
109
+ throw error;
110
+ }
111
+ };
112
+ }
113
+ export {
114
+ createLoggingMiddleware
115
+ };
116
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/createLoggingMiddleware.ts"],"sourcesContent":["import type { SagaMiddleware, SagaPipelineContext, Logger } from \"@saga-bus/core\";\nimport type { LoggingMiddlewareOptions, LogLevel, LogEventType } from \"./types.js\";\n\n/**\n * Log level priorities for filtering.\n */\nconst LOG_LEVEL_PRIORITY: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n};\n\n/**\n * Default console-based logger.\n */\nconst defaultLogger: Logger = {\n debug: (message, meta) => console.debug(`[saga-bus] ${message}`, meta ?? \"\"),\n info: (message, meta) => console.info(`[saga-bus] ${message}`, meta ?? \"\"),\n warn: (message, meta) => console.warn(`[saga-bus] ${message}`, meta ?? \"\"),\n error: (message, meta) => console.error(`[saga-bus] ${message}`, meta ?? \"\"),\n};\n\n/**\n * Create a logging middleware for saga execution.\n *\n * @example\n * ```typescript\n * const loggingMiddleware = createLoggingMiddleware({\n * level: \"debug\",\n * logPayload: true,\n * });\n *\n * const bus = createBus({\n * transport,\n * sagas: [...],\n * middleware: [loggingMiddleware],\n * });\n * ```\n */\nexport function createLoggingMiddleware(\n options: LoggingMiddlewareOptions = {}\n): SagaMiddleware {\n const {\n logger = defaultLogger,\n level = \"info\",\n logPayload = false,\n logState = false,\n filter,\n enrichMeta,\n } = options;\n\n const minPriority = LOG_LEVEL_PRIORITY[level];\n\n /**\n * Log an event if it meets the level threshold.\n */\n function log(\n eventLevel: LogLevel,\n eventType: LogEventType,\n message: string,\n meta: Record<string, unknown>\n ): void {\n if (LOG_LEVEL_PRIORITY[eventLevel] < minPriority) {\n return;\n }\n\n if (filter && !filter(eventType, meta)) {\n return;\n }\n\n const enrichedMeta = enrichMeta ? enrichMeta(meta) : meta;\n const finalMeta = { ...enrichedMeta, event: eventType };\n\n switch (eventLevel) {\n case \"debug\":\n logger.debug(message, finalMeta);\n break;\n case \"info\":\n logger.info(message, finalMeta);\n break;\n case \"warn\":\n logger.warn(message, finalMeta);\n break;\n case \"error\":\n logger.error(message, finalMeta);\n break;\n }\n }\n\n /**\n * Build base metadata from pipeline context.\n */\n function baseMeta(ctx: SagaPipelineContext): Record<string, unknown> {\n const meta: Record<string, unknown> = {\n sagaName: ctx.sagaName,\n correlationId: ctx.correlationId,\n messageId: ctx.envelope.id,\n messageType: ctx.envelope.type,\n };\n\n if (ctx.sagaId) {\n meta.sagaId = ctx.sagaId;\n }\n\n if (logPayload) {\n meta.payload = ctx.envelope.payload;\n }\n\n return meta;\n }\n\n return async (ctx: SagaPipelineContext, next: () => Promise<void>) => {\n const startTime = Date.now();\n\n // Log message received\n log(\"debug\", \"saga.message.received\", \"Message received\", {\n ...baseMeta(ctx),\n headers: ctx.envelope.headers,\n });\n\n // Log handler start\n log(\"debug\", \"saga.handler.start\", \"Handler starting\", baseMeta(ctx));\n\n try {\n await next();\n\n const duration = Date.now() - startTime;\n\n // Determine what happened\n const isNew = ctx.preState === undefined && ctx.postState !== undefined;\n const isCompleted = ctx.postState?.metadata?.isCompleted === true;\n const wasAlreadyCompleted = ctx.preState?.metadata?.isCompleted === true;\n\n // Build result metadata\n const resultMeta: Record<string, unknown> = {\n ...baseMeta(ctx),\n durationMs: duration,\n };\n\n if (ctx.sagaId) {\n resultMeta.sagaId = ctx.sagaId;\n }\n\n if (logState && ctx.postState) {\n resultMeta.state = ctx.postState;\n }\n\n if (ctx.postState) {\n resultMeta.version = ctx.postState.metadata.version;\n }\n\n // Log appropriate event\n if (isNew) {\n log(\"info\", \"saga.state.created\", \"Saga instance created\", resultMeta);\n } else if (isCompleted && !wasAlreadyCompleted) {\n log(\"info\", \"saga.state.completed\", \"Saga completed\", resultMeta);\n } else if (ctx.postState) {\n log(\"debug\", \"saga.state.updated\", \"Saga state updated\", resultMeta);\n }\n\n // Log handler success\n log(\"debug\", \"saga.handler.success\", \"Handler completed successfully\", {\n ...baseMeta(ctx),\n durationMs: duration,\n });\n } catch (error) {\n const duration = Date.now() - startTime;\n\n // Log handler error\n log(\"error\", \"saga.handler.error\", \"Handler failed\", {\n ...baseMeta(ctx),\n durationMs: duration,\n error: error instanceof Error ? error.message : String(error),\n errorType: error instanceof Error ? error.name : \"UnknownError\",\n stack: error instanceof Error ? error.stack : undefined,\n });\n\n // Re-throw to let error handling proceed\n throw error;\n }\n };\n}\n"],"mappings":";AAMA,IAAM,qBAA+C;AAAA,EACnD,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AACT;AAKA,IAAM,gBAAwB;AAAA,EAC5B,OAAO,CAAC,SAAS,SAAS,QAAQ,MAAM,cAAc,OAAO,IAAI,QAAQ,EAAE;AAAA,EAC3E,MAAM,CAAC,SAAS,SAAS,QAAQ,KAAK,cAAc,OAAO,IAAI,QAAQ,EAAE;AAAA,EACzE,MAAM,CAAC,SAAS,SAAS,QAAQ,KAAK,cAAc,OAAO,IAAI,QAAQ,EAAE;AAAA,EACzE,OAAO,CAAC,SAAS,SAAS,QAAQ,MAAM,cAAc,OAAO,IAAI,QAAQ,EAAE;AAC7E;AAmBO,SAAS,wBACd,UAAoC,CAAC,GACrB;AAChB,QAAM;AAAA,IACJ,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,aAAa;AAAA,IACb,WAAW;AAAA,IACX;AAAA,IACA;AAAA,EACF,IAAI;AAEJ,QAAM,cAAc,mBAAmB,KAAK;AAK5C,WAAS,IACP,YACA,WACA,SACA,MACM;AACN,QAAI,mBAAmB,UAAU,IAAI,aAAa;AAChD;AAAA,IACF;AAEA,QAAI,UAAU,CAAC,OAAO,WAAW,IAAI,GAAG;AACtC;AAAA,IACF;AAEA,UAAM,eAAe,aAAa,WAAW,IAAI,IAAI;AACrD,UAAM,YAAY,EAAE,GAAG,cAAc,OAAO,UAAU;AAEtD,YAAQ,YAA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W,UAAU,IAAI,UAAU,SAAS;AAAA,MAC9C;AAGA,UAAI,OAAO;AACT,YAAI,QAAQ,sBAAsB,yBAAyB,UAAU;AAAA,MACvE,WAAW,eAAe,CAAC,qBAAqB;AAC9C,YAAI,QAAQ,wBAAwB,kBAAkB,UAAU;AAAA,MAClE,WAAW,IAAI,WAAW;AACxB,YAAI,SAAS,sBAAsB,sBAAsB,UAAU;AAAA,MACrE;AAGA,UAAI,SAAS,wBAAwB,kCAAkC;AAAA,QACrE,GAAG,SAAS,GAAG;AAAA,QACf,YAAY;AAAA,MACd,CAAC;AAAA,IACH,SAAS,OAAO;AACd,YAAM,WAAW,KAAK,IAAI,IAAI;AAG9B,UAAI,SAAS,sBAAsB,kBAAkB;AAAA,QACnD,GAAG,SAAS,GAAG;AAAA,QACf,YAAY;AAAA,QACZ,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,QAC5D,WAAW,iBAAiB,QAAQ,MAAM,OAAO;AAAA,QACjD,OAAO,iBAAiB,QAAQ,MAAM,QAAQ;AAAA,MAChD,CAAC;AAGD,YAAM;AAAA,IACR;AAAA,EACF;AACF;","names":[]}
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "@saga-bus/middleware-logging",
3
+ "version": "1.0.0",
4
+ "description": "Structured logging middleware for saga-bus",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js",
13
+ "require": "./dist/index.cjs"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "README.md"
19
+ ],
20
+ "publishConfig": {
21
+ "access": "public"
22
+ },
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "https://github.com/deanforan/saga-bus.git",
26
+ "directory": "packages/middleware-logging"
27
+ },
28
+ "bugs": {
29
+ "url": "https://github.com/deanforan/saga-bus/issues"
30
+ },
31
+ "homepage": "https://github.com/deanforan/saga-bus#readme",
32
+ "keywords": [
33
+ "saga",
34
+ "message-bus",
35
+ "middleware",
36
+ "logging",
37
+ "observability"
38
+ ],
39
+ "dependencies": {
40
+ "@saga-bus/core": "0.1.0"
41
+ },
42
+ "devDependencies": {
43
+ "tsup": "^8.0.0",
44
+ "typescript": "^5.9.2",
45
+ "vitest": "^3.0.0",
46
+ "@repo/eslint-config": "0.0.0",
47
+ "@repo/typescript-config": "0.0.0"
48
+ },
49
+ "peerDependencies": {
50
+ "@saga-bus/core": ">=0.1.0"
51
+ },
52
+ "scripts": {
53
+ "build": "tsup",
54
+ "dev": "tsup --watch",
55
+ "lint": "eslint src/",
56
+ "check-types": "tsc --noEmit",
57
+ "test": "vitest run",
58
+ "test:watch": "vitest"
59
+ }
60
+ }