sm-utility 2.4.25 → 2.4.26

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.
@@ -1,5 +1,5 @@
1
1
  import { MetadataModel } from './metadata.model';
2
- import { LeveledLogMethod } from 'winston';
2
+ import { LeveledLogMethod, Logger } from 'winston';
3
3
  type LogData<T> = {
4
4
  context?: T;
5
5
  };
@@ -10,9 +10,10 @@ type EnhancedLogParams<T, E> = {
10
10
  error?: E;
11
11
  };
12
12
  export declare abstract class Command {
13
- protected readonly className: string;
14
- protected readonly metadata: MetadataModel;
15
- protected readonly logger: import("winston").Logger;
13
+ protected className?: string | undefined;
14
+ protected metadata?: MetadataModel | undefined;
15
+ private loggerInstance;
16
+ private lastTime;
16
17
  private startTime;
17
18
  /**
18
19
  * Creates a new instance of the Command class.
@@ -21,7 +22,7 @@ export declare abstract class Command {
21
22
  * @param metadata - (Optional) A metadata model containing additional information for the command.
22
23
  * If not provided, a new `MetadataModel` will be created with a randomly generated `auditUuid`.
23
24
  */
24
- constructor(className: string, metadata?: MetadataModel);
25
+ constructor(className?: string | undefined, metadata?: MetadataModel | undefined);
25
26
  /**
26
27
  * Executes the command logic. This method must be implemented by any class extending the Command base class.
27
28
  *
@@ -48,6 +49,19 @@ export declare abstract class Command {
48
49
  * }
49
50
  */
50
51
  abstract execute(params?: any): Promise<any>;
52
+ /**
53
+ * Sets the logger of the command.
54
+ * @param logger - The logger to be used for the command.
55
+ * @returns The command instance.
56
+ */
57
+ withLogger(customLogger: Logger): this;
58
+ protected get logger(): Logger;
59
+ /**
60
+ * Sets the metadata of the command that will be included in log messages.
61
+ * @param metadata - The metadata of the command.
62
+ * @returns The command instance.
63
+ */
64
+ withMetadata(metadata: MetadataModel): this;
51
65
  /**
52
66
  * Logs that the command has been initiated.
53
67
  * @param logData Optional contextual data for the log.
@@ -64,6 +78,14 @@ export declare abstract class Command {
64
78
  * @param logData Optional contextual data for the log.
65
79
  */
66
80
  protected logUnexpectedFailed<T>(error: Error, logData?: LogData<T>): void;
81
+ protected logExpectedFailed<T>(error: Error, logData?: LogData<T>): void;
82
+ /**
83
+ * Logs that the command has been interrupted.
84
+ * @param error The error that was thrown.
85
+ * @param logData Optional contextual data for the log.
86
+ */
87
+ protected logInterruptionError<T>(error: Error, logData?: LogData<T>): void;
88
+ protected logEarlyFinish<T>(logData?: LogData<T>): void;
67
89
  /**
68
90
  * Logs detailed information about the current operation, optionally including execution time and error details.
69
91
  *
@@ -84,7 +106,7 @@ export declare abstract class Command {
84
106
  * @example
85
107
  * // Log a successful operation
86
108
  * this.enhancedLog({
87
- * logMethod: this.logger.info,
109
+ * logMethod: this.logger.info.bind(this.logger),
88
110
  * message: 'Operation finished successfully',
89
111
  * logData: { userId: '12345' },
90
112
  * });
@@ -92,7 +114,7 @@ export declare abstract class Command {
92
114
  * @example
93
115
  * // Log a failed operation with an error
94
116
  * this.enhancedLog({
95
- * logMethod: this.logger.error,
117
+ * logMethod: this.logger.error.bind(this.logger),
96
118
  * message: 'Operation failed',
97
119
  * logData: { userId: '12345' },
98
120
  * error: new Error('Unexpected error'),
@@ -101,12 +123,13 @@ export declare abstract class Command {
101
123
  * @example
102
124
  * // Log an initiated operation
103
125
  * this.enhancedLog({
104
- * logMethod: this.logger.info,
126
+ * logMethod: this.logger.info.bind(this.logger),
105
127
  * message: 'Operation initiated',
106
128
  * });
107
129
  */
108
130
  protected enhancedLog<T, E>({ logMethod, message, logData, error, }: EnhancedLogParams<T, E>): void;
109
- getExecutionTime(): string;
131
+ getAccumulatedExecutionTime(): string;
132
+ getExecutionTimeSinceLastTimestamp(): string;
110
133
  private buildLogData;
111
134
  }
112
135
  export {};
@@ -4,6 +4,7 @@ exports.Command = void 0;
4
4
  const logger_1 = require("../logger");
5
5
  const metadata_model_1 = require("./metadata.model");
6
6
  const uuid_1 = require("uuid");
7
+ const tracing_1 = require("../tracing");
7
8
  class Command {
8
9
  /**
9
10
  * Creates a new instance of the Command class.
@@ -12,13 +13,48 @@ class Command {
12
13
  * @param metadata - (Optional) A metadata model containing additional information for the command.
13
14
  * If not provided, a new `MetadataModel` will be created with a randomly generated `auditUuid`.
14
15
  */
15
- constructor(className, metadata = new metadata_model_1.MetadataModel({
16
- auditUuid: (0, uuid_1.v4)(),
17
- })) {
16
+ constructor(className, metadata) {
18
17
  this.className = className;
19
18
  this.metadata = metadata;
20
- this.logger = logger_1.logger;
21
- this.startTime = performance.now();
19
+ this.className = this.constructor.name;
20
+ if (!this.metadata) {
21
+ this.metadata = new metadata_model_1.MetadataModel({
22
+ auditUuid: (0, uuid_1.v4)(),
23
+ });
24
+ }
25
+ const startTime = performance.now();
26
+ this.startTime = startTime;
27
+ this.lastTime = startTime;
28
+ }
29
+ /**
30
+ * Sets the logger of the command.
31
+ * @param logger - The logger to be used for the command.
32
+ * @returns The command instance.
33
+ */
34
+ withLogger(customLogger) {
35
+ this.loggerInstance = customLogger.child({
36
+ 'command.name': this.className,
37
+ });
38
+ return this;
39
+ }
40
+ get logger() {
41
+ if (!this.loggerInstance) {
42
+ this.loggerInstance = logger_1.logger.child({
43
+ 'command.name': this.className,
44
+ 'trace.id': tracing_1.TracingContextProvider.getTraceId(),
45
+ 'span.id': tracing_1.TracingContextProvider.getSpanId(),
46
+ });
47
+ }
48
+ return this.loggerInstance;
49
+ }
50
+ /**
51
+ * Sets the metadata of the command that will be included in log messages.
52
+ * @param metadata - The metadata of the command.
53
+ * @returns The command instance.
54
+ */
55
+ withMetadata(metadata) {
56
+ this.metadata = metadata;
57
+ return this;
22
58
  }
23
59
  /**
24
60
  * Logs that the command has been initiated.
@@ -26,7 +62,7 @@ class Command {
26
62
  */
27
63
  logInitiated(logData) {
28
64
  this.enhancedLog({
29
- logMethod: this.logger.info,
65
+ logMethod: this.logger.info.bind(this.logger),
30
66
  message: `${this.className} initiated`,
31
67
  logData,
32
68
  });
@@ -37,7 +73,7 @@ class Command {
37
73
  */
38
74
  logFinished(logData) {
39
75
  this.enhancedLog({
40
- logMethod: this.logger.info,
76
+ logMethod: this.logger.info.bind(this.logger),
41
77
  message: `${this.className} finished`,
42
78
  logData,
43
79
  });
@@ -49,12 +85,40 @@ class Command {
49
85
  */
50
86
  logUnexpectedFailed(error, logData) {
51
87
  this.enhancedLog({
52
- logMethod: this.logger.error,
53
- message: `${this.className} failed`,
88
+ logMethod: this.logger.error.bind(this.logger),
89
+ message: `${this.className} unexpected failed`,
90
+ logData,
91
+ error,
92
+ });
93
+ }
94
+ logExpectedFailed(error, logData) {
95
+ this.enhancedLog({
96
+ logMethod: this.logger.error.bind(this.logger),
97
+ message: `${this.className} expected failed`,
54
98
  logData,
55
99
  error,
56
100
  });
57
101
  }
102
+ /**
103
+ * Logs that the command has been interrupted.
104
+ * @param error The error that was thrown.
105
+ * @param logData Optional contextual data for the log.
106
+ */
107
+ logInterruptionError(error, logData) {
108
+ this.enhancedLog({
109
+ logMethod: this.logger.error.bind(this.logger),
110
+ message: `${this.className} interrupted`,
111
+ logData,
112
+ error,
113
+ });
114
+ }
115
+ logEarlyFinish(logData) {
116
+ this.enhancedLog({
117
+ logMethod: this.logger.info.bind(this.logger),
118
+ message: `${this.className} finished early`,
119
+ logData,
120
+ });
121
+ }
58
122
  /**
59
123
  * Logs detailed information about the current operation, optionally including execution time and error details.
60
124
  *
@@ -75,7 +139,7 @@ class Command {
75
139
  * @example
76
140
  * // Log a successful operation
77
141
  * this.enhancedLog({
78
- * logMethod: this.logger.info,
142
+ * logMethod: this.logger.info.bind(this.logger),
79
143
  * message: 'Operation finished successfully',
80
144
  * logData: { userId: '12345' },
81
145
  * });
@@ -83,7 +147,7 @@ class Command {
83
147
  * @example
84
148
  * // Log a failed operation with an error
85
149
  * this.enhancedLog({
86
- * logMethod: this.logger.error,
150
+ * logMethod: this.logger.error.bind(this.logger),
87
151
  * message: 'Operation failed',
88
152
  * logData: { userId: '12345' },
89
153
  * error: new Error('Unexpected error'),
@@ -92,7 +156,7 @@ class Command {
92
156
  * @example
93
157
  * // Log an initiated operation
94
158
  * this.enhancedLog({
95
- * logMethod: this.logger.info,
159
+ * logMethod: this.logger.info.bind(this.logger),
96
160
  * message: 'Operation initiated',
97
161
  * });
98
162
  */
@@ -102,7 +166,7 @@ class Command {
102
166
  };
103
167
  //* Add `executionTime` if the message is not about initiation
104
168
  if (!message.includes('initiated')) {
105
- logPayload.executionTime = this.getExecutionTime();
169
+ logPayload.executionTime = this.getAccumulatedExecutionTime();
106
170
  }
107
171
  //* Add error details if present
108
172
  if (error) {
@@ -111,7 +175,7 @@ class Command {
111
175
  //* Log the message with the appropriate level
112
176
  logMethod(message, logPayload);
113
177
  }
114
- getExecutionTime() {
178
+ getAccumulatedExecutionTime() {
115
179
  const executionTime = performance.now() - this.startTime;
116
180
  if (executionTime >= 1000) {
117
181
  //* Converting to seconds if the execution time is greater than 1000ms
@@ -119,6 +183,15 @@ class Command {
119
183
  }
120
184
  return `${executionTime.toFixed(2)}ms`;
121
185
  }
186
+ getExecutionTimeSinceLastTimestamp() {
187
+ const now = performance.now();
188
+ const executionTime = now - this.lastTime;
189
+ this.lastTime = now;
190
+ if (executionTime >= 1000) {
191
+ return `${(executionTime / 1000).toFixed(2)}s`;
192
+ }
193
+ return `${executionTime.toFixed(2)}ms`;
194
+ }
122
195
  buildLogData(logData) {
123
196
  var _a;
124
197
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sm-utility",
3
- "version": "2.4.25",
3
+ "version": "2.4.26",
4
4
  "description": "reusable utility codes for sm projects",
5
5
  "main": "index.js",
6
6
  "types": "./index.d.ts",