node-ansi-logger 3.0.0 → 3.1.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/dist/logger.js CHANGED
@@ -1,31 +1,7 @@
1
- /* eslint-disable no-console */
2
- /**
3
- * This file contains the AnsiLogger .
4
- *
5
- * @file logger.ts
6
- * @author Luca Liguori
7
- * @date 2023-06-01
8
- * @version 2.0.0
9
- *
10
- * Copyright 2023, 2024, 2025 Luca Liguori.
11
- *
12
- * Licensed under the Apache License, Version 2.0 (the "License");
13
- * you may not use this file except in compliance with the License.
14
- * You may obtain a copy of the License at
15
- *
16
- * http://www.apache.org/licenses/LICENSE-2.0
17
- *
18
- * Unless required by applicable law or agreed to in writing, software
19
- * distributed under the License is distributed on an "AS IS" BASIS,
20
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21
- * See the License for the specific language governing permissions and
22
- * limitations under the License.
23
- */
24
- import path from 'path';
1
+ import path from 'node:path';
2
+ import * as fs from 'node:fs';
3
+ import * as os from 'node:os';
25
4
  import { stringify } from './stringify.js';
26
- import * as fs from 'fs';
27
- import * as os from 'os';
28
- // ANSI color codes and styles are defined here for use in the logger
29
5
  export const RESET = '';
30
6
  export const BRIGHT = '';
31
7
  export const DIM = '';
@@ -50,28 +26,23 @@ export const CYAN = '';
50
26
  export const LIGHT_GREY = '';
51
27
  export const GREY = '';
52
28
  export const WHITE = '';
53
- // ANSI color codes short form to use in the logger
54
- export const db = ''; // Debug 247
55
- export const nf = ''; // Info 255
56
- export const nt = ''; // Notice
57
- export const wr = ''; // Warn 220
58
- export const er = ''; // Error
59
- export const ft = ''; // Fatal
60
- export const rs = ''; // Reset colors to default foreground and background
61
- export const rk = ''; // Erase from cursor
62
- // Used internally by plugins
63
- export const dn = ''; // Display name device
64
- export const gn = ''; // Display name group
65
- export const idn = ''; // Inverted display name device
66
- export const ign = ''; // Inverted display name group
67
- export const zb = ''; // Zigbee
68
- export const hk = ''; // Homekit
69
- export const pl = ''; // payload
70
- export const id = ''; // id or ieee_address or UUID
71
- export const or = ''; // history
72
- /**
73
- * LogLevel enumeration to specify the logging level.
74
- */
29
+ export const db = '';
30
+ export const nf = '';
31
+ export const nt = '';
32
+ export const wr = '';
33
+ export const er = '';
34
+ export const ft = '';
35
+ export const rs = '';
36
+ export const rk = '';
37
+ export const dn = '';
38
+ export const gn = '';
39
+ export const idn = '';
40
+ export const ign = '';
41
+ export const zb = '';
42
+ export const hk = '';
43
+ export const pl = '';
44
+ export const id = '';
45
+ export const or = '';
75
46
  export var LogLevel;
76
47
  (function (LogLevel) {
77
48
  LogLevel["NONE"] = "";
@@ -82,9 +53,6 @@ export var LogLevel;
82
53
  LogLevel["ERROR"] = "error";
83
54
  LogLevel["FATAL"] = "fatal";
84
55
  })(LogLevel || (LogLevel = {}));
85
- /**
86
- * TimestampFormat enumeration to specify the format of timestamps in log messages.
87
- */
88
56
  export var TimestampFormat;
89
57
  (function (TimestampFormat) {
90
58
  TimestampFormat[TimestampFormat["ISO"] = 0] = "ISO";
@@ -95,7 +63,6 @@ export var TimestampFormat;
95
63
  TimestampFormat[TimestampFormat["HOMEBRIDGE"] = 5] = "HOMEBRIDGE";
96
64
  TimestampFormat[TimestampFormat["CUSTOM"] = 6] = "CUSTOM";
97
65
  })(TimestampFormat || (TimestampFormat = {}));
98
- // Initialize the global variables
99
66
  if (typeof globalThis.__AnsiLoggerCallback__ === 'undefined')
100
67
  globalThis.__AnsiLoggerCallback__ = undefined;
101
68
  if (typeof globalThis.__AnsiLoggerCallbackLoglevel__ === 'undefined')
@@ -106,10 +73,6 @@ if (typeof globalThis.__AnsiLoggerFileLoglevel__ === 'undefined')
106
73
  globalThis.__AnsiLoggerFileLoglevel__ = undefined;
107
74
  if (typeof globalThis.__AnsiLoggerFileLogSize__ === 'undefined')
108
75
  globalThis.__AnsiLoggerFileLogSize__ = undefined;
109
- /**
110
- * AnsiLogger provides a customizable logging utility with ANSI color support.
111
- * It allows for various configurations such as enabling debug logs, customizing log name, and more.
112
- */
113
76
  export class AnsiLogger {
114
77
  _extLog;
115
78
  _logName;
@@ -121,140 +84,74 @@ export class AnsiLogger {
121
84
  _logCustomTimestampFormat;
122
85
  _logTimeStampColor = '';
123
86
  _logNameColor = '';
124
- _maxFileSize = 100000000; // 100MB
87
+ _maxFileSize = 100000000;
125
88
  logStartTime;
126
89
  callback = undefined;
127
- /**
128
- * Constructs a new AnsiLogger instance with optional configuration parameters.
129
- * @param {AnsiLoggerParams} optionalParams - Configuration options for the logger.
130
- */
131
90
  constructor(params) {
132
91
  this._extLog = params.extLog;
133
92
  this._logName = params.logName ?? 'NodeAnsiLogger';
134
- this._logLevel = params.logLevel ?? (params.logDebug === true ? "debug" /* LogLevel.DEBUG */ : "info" /* LogLevel.INFO */);
93
+ this._logLevel = params.logLevel ?? (params.logDebug === true ? "debug" : "info");
135
94
  this._logWithColors = params.logWithColors ?? true;
136
- this._logTimestampFormat = params.logTimestampFormat ?? 3 /* TimestampFormat.LOCAL_DATE_TIME */;
95
+ this._logTimestampFormat = params.logTimestampFormat ?? 3;
137
96
  this._logCustomTimestampFormat = params.logCustomTimestampFormat ?? 'yyyy-MM-dd HH:mm:ss';
138
97
  this.logStartTime = 0;
139
98
  }
140
- /**
141
- * Gets the name of the logger.
142
- * @returns {string} The logger name.
143
- */
144
99
  get logName() {
145
100
  return this._logName;
146
101
  }
147
- /**
148
- * Sets the log name for the logger.
149
- * @param {string} name - The logger name to set.
150
- */
151
102
  set logName(name) {
152
103
  this._logName = name;
153
104
  }
154
- /**
155
- * Gets the log level of the logger.
156
- * @returns {LogLevel} The log level.
157
- */
158
105
  get logLevel() {
159
106
  return this._logLevel;
160
107
  }
161
- /**
162
- * Sets the log level for the logger.
163
- * @param {LogLevel} logLevel - The log level to set.
164
- */
165
108
  set logLevel(logLevel) {
166
109
  this._logLevel = logLevel;
167
110
  }
168
- /**
169
- * Gets the logWithColors flag of the logger.
170
- * @returns {boolean} The logWithColors parameter.
171
- */
172
111
  get logWithColors() {
173
112
  return this._logWithColors;
174
113
  }
175
- /**
176
- * Sets the logWithColors flag of the logger.
177
- * @param {boolean} logWithColors - The logWithColors parameter to set.
178
- */
179
114
  set logWithColors(logWithColors) {
180
115
  this._logWithColors = logWithColors;
181
116
  }
182
- /**
183
- * Gets the log name color string of the logger.
184
- *
185
- * @returns {string} The log name color string.
186
- */
187
117
  get logNameColor() {
188
118
  return this._logNameColor;
189
119
  }
190
- /**
191
- * Sets the log name color string for the logger.
192
- *
193
- * @param {string} color - The logger name color string to set.
194
- */
195
120
  set logNameColor(color) {
196
121
  this._logNameColor = color;
197
122
  }
198
- /**
199
- * Gets the log timestamp format of the logger.
200
- * @returns {TimestampFormat} The log timestamp format.
201
- */
202
123
  get logTimestampFormat() {
203
124
  return this._logTimestampFormat;
204
125
  }
205
- /**
206
- * Sets the log timestamp format for the logger.
207
- * @param {TimestampFormat} logTimestampFormat - The log timestamp format to set.
208
- */
209
126
  set logTimestampFormat(logTimestampFormat) {
210
127
  this._logTimestampFormat = logTimestampFormat;
211
128
  }
212
- /**
213
- * Gets the custom log timestamp format of the logger.
214
- * @returns {string} The custom log timestamp format.
215
- */
216
129
  get logCustomTimestampFormat() {
217
130
  return this._logCustomTimestampFormat;
218
131
  }
219
- /**
220
- * Sets the custom log timestamp format for the logger.
221
- * @param {string} logCustomTimestampFormat - The custom log timestamp format to set.
222
- */
223
132
  set logCustomTimestampFormat(logCustomTimestampFormat) {
224
133
  this._logCustomTimestampFormat = logCustomTimestampFormat;
225
134
  }
226
- /**
227
- * Gets the file path of the log.
228
- *
229
- * @returns {string | undefined} The file path of the log, or undefined if not set.
230
- */
231
135
  get logFilePath() {
232
136
  return this._logFilePath;
233
137
  }
234
- /**
235
- * Sets the file path for logging.
236
- *
237
- * @param {string | undefined} filePath - The file path to set for logging.
238
- */
239
138
  set logFilePath(filePath) {
240
139
  if (filePath && typeof filePath === 'string' && filePath !== '') {
241
- // Convert relative path to absolute path
242
140
  try {
243
141
  this._logFilePath = path.resolve(filePath);
244
142
  }
245
143
  catch (error) {
246
- console.error(`Error resolving log file path ${CYAN}${filePath}${er}: ${error instanceof Error ? error.message : error}`);
144
+ console.error(`Error resolving log file path ${CYAN}${filePath}${er}: ${error}`);
247
145
  this._logFilePath = undefined;
248
146
  this._logFileSize = undefined;
249
147
  return;
250
148
  }
251
- // Check if the file exists and unlink
252
149
  if (this._logFilePath && fs.existsSync(this._logFilePath)) {
253
150
  try {
254
151
  fs.unlinkSync(this._logFilePath);
255
152
  }
256
153
  catch (error) {
257
- console.error(`${er}Error unlinking the log file ${CYAN}${this._logFilePath}${er}: ${error instanceof Error ? error.message : error}`);
154
+ console.error(`${er}Error unlinking the log file ${CYAN}${this._logFilePath}${er}: ${error}`);
258
155
  this._logFilePath = undefined;
259
156
  this._logFileSize = undefined;
260
157
  return;
@@ -267,40 +164,19 @@ export class AnsiLogger {
267
164
  this._logFileSize = undefined;
268
165
  }
269
166
  }
270
- /**
271
- * Gets the size of log file.
272
- *
273
- * @returns {number | undefined} The size of log file, or undefined if not set.
274
- */
275
167
  get logFileSize() {
276
168
  return this._logFilePath && this._logFileSize ? this._logFileSize : undefined;
277
169
  }
278
- /**
279
- * Gets the max file size of the file loggers.
280
- * @returns {number} The current maxFileSize.
281
- */
282
170
  get maxFileSize() {
283
171
  return this._maxFileSize;
284
172
  }
285
- /**
286
- * Sets the max file size of the file loggers.
287
- * @param {number} maxFileSize - The maxFileSize to set.
288
- */
289
173
  set maxFileSize(maxFileSize) {
290
- this._maxFileSize = Math.min(maxFileSize, 100000000); // 100MB
174
+ this._maxFileSize = Math.min(maxFileSize, 500000000);
291
175
  }
292
- /**
293
- * Starts a timer with an optional message.
294
- * @param {string} message - The message to log when starting the timer.
295
- */
296
176
  startTimer(message) {
297
177
  this.logStartTime = Date.now();
298
178
  this.info(`Timer started ${message}`);
299
179
  }
300
- /**
301
- * Stops the timer started by startTimer and logs the elapsed time.
302
- * @param {string} message - The message to log along with the elapsed time.
303
- */
304
180
  stopTimer(message) {
305
181
  if (this.logStartTime !== 0) {
306
182
  const timePassed = Date.now() - this.logStartTime;
@@ -308,36 +184,17 @@ export class AnsiLogger {
308
184
  }
309
185
  this.logStartTime = 0;
310
186
  }
311
- /**
312
- * Sets the callback function to be used by the logger.
313
- * @param {AnsiLoggerCallback} callback - The callback function.
314
- */
315
187
  setCallback(callback) {
316
188
  this.callback = callback;
317
189
  }
318
- /**
319
- * Gets the callback function currently used by the logger.
320
- * @returns {AnsiLoggerCallback | undefined} The callback function.
321
- */
322
190
  getCallback() {
323
191
  return this.callback;
324
192
  }
325
- /**
326
- * Sets the global callback function to be used by the logger.
327
- * @param {AnsiLoggerCallback | undefined} callback - The callback function.
328
- * @param {LogLevel} [callbackLevel=LogLevel.DEBUG] - The log level of the log file (default LogLevel.DEBUG).
329
- *
330
- * @returns {AnsiLoggerCallback | undefined} The path name of the log file.
331
- */
332
- static setGlobalCallback(callback, callbackLevel = "debug" /* LogLevel.DEBUG */) {
193
+ static setGlobalCallback(callback, callbackLevel = "debug") {
333
194
  __AnsiLoggerCallback__ = callback;
334
195
  __AnsiLoggerCallbackLoglevel__ = callbackLevel;
335
196
  return __AnsiLoggerCallback__;
336
197
  }
337
- /**
338
- * Gets the global callback function currently used by the logger.
339
- * @returns {AnsiLoggerCallback | undefined} The callback function.
340
- */
341
198
  static getGlobalCallback() {
342
199
  if (__AnsiLoggerCallback__) {
343
200
  return __AnsiLoggerCallback__;
@@ -346,11 +203,6 @@ export class AnsiLogger {
346
203
  return undefined;
347
204
  }
348
205
  }
349
- /**
350
- * Gets the global callback log level used by the logger.
351
- *
352
- * @returns {LogLevel | undefined} The log level of the global callback.
353
- */
354
206
  static getGlobalCallbackLevel() {
355
207
  if (__AnsiLoggerCallbackLoglevel__) {
356
208
  return __AnsiLoggerCallbackLoglevel__;
@@ -359,36 +211,19 @@ export class AnsiLogger {
359
211
  return undefined;
360
212
  }
361
213
  }
362
- /**
363
- * Sets the global callback log level for the logger.
364
- *
365
- * @param {LogLevel} logLevel - The log level to set. Defaults to LogLevel.DEBUG.
366
- *
367
- * @returns {LogLevel | undefined} The log level that was set.
368
- */
369
- static setGlobalCallbackLevel(logLevel = "debug" /* LogLevel.DEBUG */) {
214
+ static setGlobalCallbackLevel(logLevel = "debug") {
370
215
  __AnsiLoggerCallbackLoglevel__ = logLevel;
371
216
  return __AnsiLoggerCallbackLoglevel__;
372
217
  }
373
- /**
374
- * Sets the global logfile to be used by the logger.
375
- * @param {string} logfilePath - The path name of the log file.
376
- * @param {LogLevel} logfileLevel - Optional: the log level of the log file. Default LogLevel.DEBUG.
377
- * @param {boolean} unlink - Optional: whether to unlink (delete) the log file if it exists. Default false.
378
- *
379
- * @returns {string | undefined} The absolute path name of the log file.
380
- */
381
- static setGlobalLogfile(logfilePath, logfileLevel = "debug" /* LogLevel.DEBUG */, unlink = false) {
218
+ static setGlobalLogfile(logfilePath, logfileLevel = "debug", unlink = false) {
382
219
  if (logfilePath && typeof logfilePath === 'string' && logfilePath !== '') {
383
- // Convert relative path to absolute path
384
220
  logfilePath = path.resolve(logfilePath);
385
- // Check if the file exists and unlink it if requested
386
221
  if (unlink && fs.existsSync(logfilePath)) {
387
222
  try {
388
223
  fs.unlinkSync(logfilePath);
389
224
  }
390
225
  catch (error) {
391
- console.error(`${er}Error unlinking the log file ${CYAN}${logfilePath}${er}: ${error instanceof Error ? error.message : error}`);
226
+ console.error(`${er}Error unlinking the log file ${CYAN}${logfilePath}${er}: ${error}`);
392
227
  }
393
228
  }
394
229
  __AnsiLoggerFilePath__ = logfilePath;
@@ -400,11 +235,6 @@ export class AnsiLogger {
400
235
  __AnsiLoggerFileLogSize__ = undefined;
401
236
  return undefined;
402
237
  }
403
- /**
404
- * Gets the global logfile currently used by the logger.
405
- *
406
- * @returns {string | undefined} The path name of the log file.
407
- */
408
238
  static getGlobalLogfile() {
409
239
  if (__AnsiLoggerFilePath__) {
410
240
  return __AnsiLoggerFilePath__;
@@ -413,11 +243,6 @@ export class AnsiLogger {
413
243
  return undefined;
414
244
  }
415
245
  }
416
- /**
417
- * Gets the global logfile log level used by the loggers.
418
- *
419
- * @returns {LogLevel | undefined} The log level of the global logfile.
420
- */
421
246
  static getGlobalLogfileLevel() {
422
247
  if (__AnsiLoggerFileLoglevel__) {
423
248
  return __AnsiLoggerFileLoglevel__;
@@ -426,65 +251,50 @@ export class AnsiLogger {
426
251
  return undefined;
427
252
  }
428
253
  }
429
- /**
430
- * Sets the global logfile log level used by the loggers.
431
- *
432
- * @param {LogLevel} logfileLevel - The global logfile log level used by the loggers.
433
- *
434
- * @returns {LogLevel | undefined} The log level of the global logfile.
435
- */
436
254
  static setGlobalLogfileLevel(logfileLevel) {
437
255
  __AnsiLoggerFileLoglevel__ = logfileLevel;
438
256
  return __AnsiLoggerFileLoglevel__;
439
257
  }
440
- /**
441
- * Determines whether a log message with the given level should be logged based on the configured log level.
442
- *
443
- * @param {LogLevel} level - The level of the log message.
444
- * @param {LogLevel | undefined} configuredLevel - The configured log level.
445
- *
446
- * @returns {boolean} A boolean indicating whether the log message should be logged.
447
- */
448
258
  shouldLog(level, configuredLevel) {
449
259
  switch (level) {
450
- case "" /* LogLevel.NONE */:
260
+ case "":
451
261
  return false;
452
- case "debug" /* LogLevel.DEBUG */:
453
- if (configuredLevel === "debug" /* LogLevel.DEBUG */) {
262
+ case "debug":
263
+ if (configuredLevel === "debug") {
454
264
  return true;
455
265
  }
456
266
  break;
457
- case "info" /* LogLevel.INFO */:
458
- if (configuredLevel === "debug" /* LogLevel.DEBUG */ || configuredLevel === "info" /* LogLevel.INFO */) {
267
+ case "info":
268
+ if (configuredLevel === "debug" || configuredLevel === "info") {
459
269
  return true;
460
270
  }
461
271
  break;
462
- case "notice" /* LogLevel.NOTICE */:
463
- if (configuredLevel === "debug" /* LogLevel.DEBUG */ || configuredLevel === "info" /* LogLevel.INFO */ || configuredLevel === "notice" /* LogLevel.NOTICE */) {
272
+ case "notice":
273
+ if (configuredLevel === "debug" || configuredLevel === "info" || configuredLevel === "notice") {
464
274
  return true;
465
275
  }
466
276
  break;
467
- case "warn" /* LogLevel.WARN */:
468
- if (configuredLevel === "debug" /* LogLevel.DEBUG */ || configuredLevel === "info" /* LogLevel.INFO */ || configuredLevel === "notice" /* LogLevel.NOTICE */ || configuredLevel === "warn" /* LogLevel.WARN */) {
277
+ case "warn":
278
+ if (configuredLevel === "debug" || configuredLevel === "info" || configuredLevel === "notice" || configuredLevel === "warn") {
469
279
  return true;
470
280
  }
471
281
  break;
472
- case "error" /* LogLevel.ERROR */:
473
- if (configuredLevel === "debug" /* LogLevel.DEBUG */ ||
474
- configuredLevel === "info" /* LogLevel.INFO */ ||
475
- configuredLevel === "notice" /* LogLevel.NOTICE */ ||
476
- configuredLevel === "warn" /* LogLevel.WARN */ ||
477
- configuredLevel === "error" /* LogLevel.ERROR */) {
282
+ case "error":
283
+ if (configuredLevel === "debug" ||
284
+ configuredLevel === "info" ||
285
+ configuredLevel === "notice" ||
286
+ configuredLevel === "warn" ||
287
+ configuredLevel === "error") {
478
288
  return true;
479
289
  }
480
290
  break;
481
- case "fatal" /* LogLevel.FATAL */:
482
- if (configuredLevel === "debug" /* LogLevel.DEBUG */ ||
483
- configuredLevel === "info" /* LogLevel.INFO */ ||
484
- configuredLevel === "notice" /* LogLevel.NOTICE */ ||
485
- configuredLevel === "warn" /* LogLevel.WARN */ ||
486
- configuredLevel === "error" /* LogLevel.ERROR */ ||
487
- configuredLevel === "fatal" /* LogLevel.FATAL */) {
291
+ case "fatal":
292
+ if (configuredLevel === "debug" ||
293
+ configuredLevel === "info" ||
294
+ configuredLevel === "notice" ||
295
+ configuredLevel === "warn" ||
296
+ configuredLevel === "error" ||
297
+ configuredLevel === "fatal") {
488
298
  return true;
489
299
  }
490
300
  break;
@@ -493,22 +303,13 @@ export class AnsiLogger {
493
303
  }
494
304
  return false;
495
305
  }
496
- /**
497
- * Formats a Date object into a custom string format.
498
- * @param {Date} date - The Date object to format.
499
- * @param {string} formatString - The string format to use.
500
- * @returns {string} The formatted date.
501
- * It only handles years, months, days, hours, minutes, and seconds
502
- * with this format 'yyyy-MM-dd HH:mm:ss'
503
- */
504
306
  formatCustomTimestamp(date, formatString) {
505
307
  const year = date.getFullYear();
506
- const month = date.getMonth() + 1; // getMonth() returns 0-11
308
+ const month = date.getMonth() + 1;
507
309
  const day = date.getDate();
508
310
  const hours = date.getHours();
509
311
  const minutes = date.getMinutes();
510
312
  const seconds = date.getSeconds();
511
- // Replace format tokens with actual values. Add more as needed.
512
313
  return formatString
513
314
  .replace('yyyy', year.toString())
514
315
  .replace('MM', month.toString().padStart(2, '0'))
@@ -517,20 +318,9 @@ export class AnsiLogger {
517
318
  .replace('mm', minutes.toString().padStart(2, '0'))
518
319
  .replace('ss', seconds.toString().padStart(2, '0'));
519
320
  }
520
- /**
521
- * Returns the current timestamp as a string.
522
- *
523
- * @returns {string} The current timestamp.
524
- */
525
321
  now() {
526
322
  return this.getTimestamp();
527
323
  }
528
- /**
529
- * Returns the timestamp based on the configured format.
530
- * If the log start time is set, it returns the time passed since the start time.
531
- * Otherwise, it returns the current timestamp based on the configured format.
532
- * @returns {string} The timestamp string.
533
- */
534
324
  getTimestamp() {
535
325
  if (this.logStartTime !== 0) {
536
326
  const timePassed = Date.now() - this.logStartTime;
@@ -539,39 +329,32 @@ export class AnsiLogger {
539
329
  else {
540
330
  let timestamp;
541
331
  switch (this._logTimestampFormat) {
542
- case 1 /* TimestampFormat.LOCAL_DATE */:
332
+ case 1:
543
333
  timestamp = new Date().toLocaleDateString();
544
334
  break;
545
- case 2 /* TimestampFormat.LOCAL_TIME */:
335
+ case 2:
546
336
  timestamp = new Date().toLocaleTimeString();
547
337
  break;
548
- case 5 /* TimestampFormat.HOMEBRIDGE */:
549
- case 3 /* TimestampFormat.LOCAL_DATE_TIME */:
338
+ case 5:
339
+ case 3:
550
340
  timestamp = new Date().toLocaleString();
551
341
  break;
552
- case 0 /* TimestampFormat.ISO */:
342
+ case 0:
553
343
  timestamp = new Date().toISOString();
554
344
  break;
555
- case 4 /* TimestampFormat.TIME_MILLIS */:
345
+ case 4:
556
346
  timestamp = `${new Date().getHours().toString().padStart(2, '0')}:${new Date().getMinutes().toString().padStart(2, '0')}:${new Date().getSeconds().toString().padStart(2, '0')}.${new Date().getMilliseconds().toString().padStart(3, '0')}`;
557
347
  break;
558
- case 6 /* TimestampFormat.CUSTOM */:
348
+ case 6:
559
349
  timestamp = this.formatCustomTimestamp(new Date(), this._logCustomTimestampFormat);
560
350
  break;
351
+ default:
352
+ timestamp = new Date().toLocaleString();
353
+ break;
561
354
  }
562
355
  return timestamp;
563
356
  }
564
357
  }
565
- /**
566
- * Writes a log message to a file.
567
- *
568
- * @param {string} filePath - The path of the file to write the log message to.
569
- * @param {LogLevel} level - The log level of the message.
570
- * @param {string} message - The log message.
571
- * @param {...any[]} parameters - Additional parameters to include in the log message.
572
- * @returns {number} - The length of the log message including the appended newline character.
573
- */
574
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
575
358
  logToFile(filePath, level, message, ...parameters) {
576
359
  const parametersString = parameters
577
360
  .map((parameter) => {
@@ -584,8 +367,6 @@ export class AnsiLogger {
584
367
  return stringify(parameter);
585
368
  case 'string':
586
369
  return parameter;
587
- case 'undefined':
588
- return 'undefined';
589
370
  case 'function':
590
371
  return '(function)';
591
372
  default:
@@ -594,9 +375,7 @@ export class AnsiLogger {
594
375
  })
595
376
  .join(' ');
596
377
  let messageLog = `[${this.getTimestamp()}] [${this._logName}] [${level}] ` + message + ' ' + parametersString;
597
- // messageLog = messageLog.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, '').replace(/[\t\n\r]/g, '');
598
378
  messageLog = messageLog
599
- // eslint-disable-next-line no-control-regex
600
379
  .replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, '')
601
380
  .replaceAll('\t', ' ')
602
381
  .replaceAll('\r', '')
@@ -604,28 +383,16 @@ export class AnsiLogger {
604
383
  fs.appendFileSync(filePath, messageLog + os.EOL);
605
384
  return messageLog.length + 1;
606
385
  }
607
- /**
608
- * Logs a message with a specific level (e.g. debug, info, notice, warn, error, fatal) and additional parameters.
609
- * This method formats the log message with ANSI colors based on the log level and other logger settings.
610
- * It supports dynamic parameters for more detailed and formatted logging.
611
- *
612
- * @param {LogLevel} level - The severity level of the log message.
613
- * @param {string} message - The primary log message to be displayed.
614
- * @param {...any[]} parameters - Additional parameters to be logged. Supports any number of parameters.
615
- */
616
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
617
386
  log(level, message, ...parameters) {
618
- const s1ln = ''; // Highlight LogName Black on Cyan
619
- const s2ln = ''; // Highlight LogName Black on White
620
- const s3ln = ''; // Highlight LogName Black on Yellow
621
- const s4ln = ''; // Highlight LogName Black on Red
387
+ const s1ln = '';
388
+ const s2ln = '';
389
+ const s3ln = '';
390
+ const s4ln = '';
622
391
  if (typeof level !== 'string' || level.startsWith === undefined || typeof message !== 'string' || message.startsWith === undefined) {
623
392
  return;
624
393
  }
625
- // Local callback
626
394
  try {
627
395
  if (this.callback !== undefined && this.shouldLog(level, this._logLevel)) {
628
- // Convert parameters to string and append to message
629
396
  const parametersString = parameters.length > 0 ? ' ' + parameters.join(' ') : '';
630
397
  const newMessage = message + parametersString;
631
398
  this.callback(level, this.getTimestamp(), this._logName, newMessage);
@@ -634,10 +401,8 @@ export class AnsiLogger {
634
401
  catch (error) {
635
402
  console.error('Error executing local callback:', error);
636
403
  }
637
- // Global callback
638
404
  try {
639
405
  if (__AnsiLoggerCallback__ && __AnsiLoggerCallback__ !== undefined && this.shouldLog(level, __AnsiLoggerCallbackLoglevel__)) {
640
- // Convert parameters to string and append to message
641
406
  const parametersString = parameters.length > 0 ? ' ' + parameters.join(' ') : '';
642
407
  const newMessage = message + parametersString;
643
408
  __AnsiLoggerCallback__(level, this.getTimestamp(), this._logName, newMessage);
@@ -646,7 +411,6 @@ export class AnsiLogger {
646
411
  catch (error) {
647
412
  console.error('Error executing global callback:', error);
648
413
  }
649
- // Local file logger
650
414
  try {
651
415
  if (this.logFilePath !== undefined && this._logFileSize !== undefined && this._logFileSize < this._maxFileSize && this.shouldLog(level, this._logLevel)) {
652
416
  const size = this.logToFile(this.logFilePath, level, message, ...parameters);
@@ -659,7 +423,6 @@ export class AnsiLogger {
659
423
  catch (error) {
660
424
  console.error(`Error writing to the local log file ${this.logFilePath}:`, error);
661
425
  }
662
- // Global file logger
663
426
  try {
664
427
  if (__AnsiLoggerFilePath__ &&
665
428
  __AnsiLoggerFilePath__ !== undefined &&
@@ -677,7 +440,7 @@ export class AnsiLogger {
677
440
  console.error(`Error writing to the global log file ${__AnsiLoggerFilePath__}:`, error);
678
441
  }
679
442
  if (this._extLog !== undefined) {
680
- if (level !== "" /* LogLevel.NONE */) {
443
+ if (level !== "") {
681
444
  this._extLog.log(level, message, ...parameters);
682
445
  }
683
446
  }
@@ -701,32 +464,32 @@ export class AnsiLogger {
701
464
  message = message.slice(1);
702
465
  }
703
466
  switch (level) {
704
- case "debug" /* LogLevel.DEBUG */:
467
+ case "debug":
705
468
  if (this.shouldLog(level, this._logLevel)) {
706
469
  console.log(`${rs}${this._logTimeStampColor}[${this.getTimestamp()}] ${logNameColor}[${this._logName}]${rs}${db}`, message + rs + rk, ...parameters);
707
470
  }
708
471
  break;
709
- case "info" /* LogLevel.INFO */:
472
+ case "info":
710
473
  if (this.shouldLog(level, this._logLevel)) {
711
474
  console.log(`${rs}${this._logTimeStampColor}[${this.getTimestamp()}] ${logNameColor}[${this._logName}]${rs}${nf}`, message + rs + rk, ...parameters);
712
475
  }
713
476
  break;
714
- case "notice" /* LogLevel.NOTICE */:
477
+ case "notice":
715
478
  if (this.shouldLog(level, this._logLevel)) {
716
479
  console.log(`${rs}${this._logTimeStampColor}[${this.getTimestamp()}] ${logNameColor}[${this._logName}]${rs}${nt}`, message + rs + rk, ...parameters);
717
480
  }
718
481
  break;
719
- case "warn" /* LogLevel.WARN */:
482
+ case "warn":
720
483
  if (this.shouldLog(level, this._logLevel)) {
721
484
  console.log(`${rs}${this._logTimeStampColor}[${this.getTimestamp()}] ${logNameColor}[${this._logName}]${rs}${wr}`, message + rs + rk, ...parameters);
722
485
  }
723
486
  break;
724
- case "error" /* LogLevel.ERROR */:
487
+ case "error":
725
488
  if (this.shouldLog(level, this._logLevel)) {
726
489
  console.log(`${rs}${this._logTimeStampColor}[${this.getTimestamp()}] ${logNameColor}[${this._logName}]${rs}${er}`, message + rs + rk, ...parameters);
727
490
  }
728
491
  break;
729
- case "fatal" /* LogLevel.FATAL */:
492
+ case "fatal":
730
493
  if (this.shouldLog(level, this._logLevel)) {
731
494
  console.log(`${rs}${this._logTimeStampColor}[${this.getTimestamp()}] ${logNameColor}[${this._logName}]${rs}${ft}`, message + rs + rk, ...parameters);
732
495
  }
@@ -737,42 +500,42 @@ export class AnsiLogger {
737
500
  }
738
501
  else {
739
502
  switch (level) {
740
- case "debug" /* LogLevel.DEBUG */:
741
- if (this._logLevel === "debug" /* LogLevel.DEBUG */) {
503
+ case "debug":
504
+ if (this._logLevel === "debug") {
742
505
  console.log(`[${this.getTimestamp()}] [${this._logName}] [${level}] ${message}`, ...parameters);
743
506
  }
744
507
  break;
745
- case "info" /* LogLevel.INFO */:
746
- if (this._logLevel === "debug" /* LogLevel.DEBUG */ || this._logLevel === "info" /* LogLevel.INFO */) {
508
+ case "info":
509
+ if (this._logLevel === "debug" || this._logLevel === "info") {
747
510
  console.log(`[${this.getTimestamp()}] [${this._logName}] [${level}] ${message}`, ...parameters);
748
511
  }
749
512
  break;
750
- case "notice" /* LogLevel.NOTICE */:
751
- if (this._logLevel === "debug" /* LogLevel.DEBUG */ || this._logLevel === "info" /* LogLevel.INFO */ || this._logLevel === "notice" /* LogLevel.NOTICE */) {
513
+ case "notice":
514
+ if (this._logLevel === "debug" || this._logLevel === "info" || this._logLevel === "notice") {
752
515
  console.log(`[${this.getTimestamp()}] [${this._logName}] [${level}] ${message}`, ...parameters);
753
516
  }
754
517
  break;
755
- case "warn" /* LogLevel.WARN */:
756
- if (this._logLevel === "debug" /* LogLevel.DEBUG */ || this._logLevel === "info" /* LogLevel.INFO */ || this._logLevel === "notice" /* LogLevel.NOTICE */ || this._logLevel === "warn" /* LogLevel.WARN */) {
518
+ case "warn":
519
+ if (this._logLevel === "debug" || this._logLevel === "info" || this._logLevel === "notice" || this._logLevel === "warn") {
757
520
  console.log(`[${this.getTimestamp()}] [${this._logName}] [${level}] ${message}`, ...parameters);
758
521
  }
759
522
  break;
760
- case "error" /* LogLevel.ERROR */:
761
- if (this._logLevel === "debug" /* LogLevel.DEBUG */ ||
762
- this._logLevel === "info" /* LogLevel.INFO */ ||
763
- this._logLevel === "notice" /* LogLevel.NOTICE */ ||
764
- this._logLevel === "warn" /* LogLevel.WARN */ ||
765
- this._logLevel === "error" /* LogLevel.ERROR */) {
523
+ case "error":
524
+ if (this._logLevel === "debug" ||
525
+ this._logLevel === "info" ||
526
+ this._logLevel === "notice" ||
527
+ this._logLevel === "warn" ||
528
+ this._logLevel === "error") {
766
529
  console.log(`[${this.getTimestamp()}] [${this._logName}] [${level}] ${message}`, ...parameters);
767
530
  }
768
531
  break;
769
- case "fatal" /* LogLevel.FATAL */:
770
- if (this._logLevel === "debug" /* LogLevel.DEBUG */ ||
771
- this._logLevel === "info" /* LogLevel.INFO */ ||
772
- this._logLevel === "notice" /* LogLevel.NOTICE */ ||
773
- this._logLevel === "warn" /* LogLevel.WARN */ ||
774
- this._logLevel === "error" /* LogLevel.ERROR */ ||
775
- this._logLevel === "fatal" /* LogLevel.FATAL */) {
532
+ case "fatal":
533
+ if (this._logLevel === "debug" ||
534
+ this._logLevel === "info" ||
535
+ this._logLevel === "notice" ||
536
+ this._logLevel === "warn" ||
537
+ this._logLevel === "error" ||
538
+ this._logLevel === "fatal") {
776
539
  console.log(`[${this.getTimestamp()}] [${this._logName}] [${level}] ${message}`, ...parameters);
777
540
  }
778
541
  break;
@@ -782,164 +545,22 @@ export class AnsiLogger {
782
545
  }
783
546
  }
784
547
  }
785
- /**
786
- * Logs a debug message if debug logging is enabled. This is a convenience method that delegates to the `log` method with the `LogLevel.DEBUG` level.
787
- *
788
- * @param {string} message - The message to log.
789
- * @param {...any[]} parameters - Additional parameters to be included in the log message. Supports any number of parameters.
790
- */
791
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
792
548
  debug(message, ...parameters) {
793
- this.log("debug" /* LogLevel.DEBUG */, message, ...parameters);
794
- }
795
- /**
796
- * Logs an informational message. This is a convenience method that delegates to the `log` method with the `LogLevel.INFO` level.
797
- *
798
- * @param {string} message - The message to log.
799
- * @param {...any[]} parameters - Additional parameters to be included in the log message. Supports any number of parameters.
800
- */
801
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
549
+ this.log("debug", message, ...parameters);
550
+ }
802
551
  info(message, ...parameters) {
803
- this.log("info" /* LogLevel.INFO */, message, ...parameters);
804
- }
805
- /**
806
- * Logs a notice message. This is a convenience method that delegates to the `log` method with the `LogLevel.NOTICE` level.
807
- *
808
- * @param {string} message - The message to log.
809
- * @param {...any[]} parameters - Additional parameters to be included in the log message. Supports any number of parameters.
810
- */
811
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
552
+ this.log("info", message, ...parameters);
553
+ }
812
554
  notice(message, ...parameters) {
813
- this.log("notice" /* LogLevel.NOTICE */, message, ...parameters);
814
- }
815
- /**
816
- * Logs a warning message. This is a convenience method that delegates to the `log` method with the `LogLevel.WARN` level.
817
- *
818
- * @param {string} message - The message to log.
819
- * @param {...any[]} parameters - Additional parameters to be included in the log message. Supports any number of parameters.
820
- */
821
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
555
+ this.log("notice", message, ...parameters);
556
+ }
822
557
  warn(message, ...parameters) {
823
- this.log("warn" /* LogLevel.WARN */, message, ...parameters);
824
- }
825
- /**
826
- * Logs an error message. This is a convenience method that delegates to the `log` method with the `LogLevel.ERROR` level.
827
- *
828
- * @param {string} message - The message to log.
829
- * @param {...any[]} parameters - Additional parameters to be included in the log message. Supports any number of parameters.
830
- */
831
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
558
+ this.log("warn", message, ...parameters);
559
+ }
832
560
  error(message, ...parameters) {
833
- this.log("error" /* LogLevel.ERROR */, message, ...parameters);
834
- }
835
- /**
836
- * Logs a fatal message. This is a convenience method that delegates to the `log` method with the `LogLevel.FATAL` level.
837
- *
838
- * @param {string} message - The message to log.
839
- * @param {...any[]} parameters - Additional parameters to be included in the log message. Supports any number of parameters.
840
- */
841
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
561
+ this.log("error", message, ...parameters);
562
+ }
842
563
  fatal(message, ...parameters) {
843
- this.log("fatal" /* LogLevel.FATAL */, message, ...parameters);
564
+ this.log("fatal", message, ...parameters);
844
565
  }
845
566
  }
846
- // Use with node dist/logger.js --testAnsiLoggerColors to test ANSI colors
847
- /*
848
- if (process.argv.includes('--testAnsiLoggerColors')) {
849
- for (let i = 0; i < 256; i++) {
850
- console.log(`[38;5;${i}mForeground color ${i.toString().padStart(3, ' ')} bright`);
851
- }
852
- console.log(`${db}Debug message${rs}`);
853
- console.log(`${nf}Info message${rs}`);
854
- console.log(`${nt}Notice message${rs}`);
855
- console.log(`${wr}Warn message${rs}`);
856
- console.log(`${er}Error message${rs}`);
857
- console.log(`${ft}Fatal message${rs}`);
858
- console.log(`${nf}Stringify payload: ${payloadStringify({ number: 1234, string: 'Text', boolean: true, null: null, undefined: undefined })}${rs}`);
859
- console.log(`${nf}Stringify color: ${colorStringify({ number: 1234, string: 'Text', boolean: true, null: null, undefined: undefined })}${rs}`);
860
- console.log(`${nf}Stringify history: ${historyStringify({ number: 1234, string: 'Text', boolean: true, null: null, undefined: undefined })}${rs}`);
861
- console.log(
862
- `${nf}Stringify mqtt: ${mqttStringify({
863
- number: 1234,
864
- string: 'Text',
865
- boolean: true,
866
- null: null,
867
- undefined: undefined,
868
- function: () => {
869
- //
870
- },
871
- })}${rs}`,
872
- );
873
- console.log(
874
- `${db}Stringify debug: ${debugStringify({ number: 1234, string: 'Text', boolean: true, null: null, undefined: undefined, object: { number: 1234, string: 'Text', boolean: true } })}${rs}`,
875
- );
876
-
877
- const logger = new AnsiLogger({ logName: 'TestLogger', logLevel: LogLevel.DEBUG, logWithColors: true, logTimestampFormat: TimestampFormat.TIME_MILLIS });
878
- logger.logFilePath = 'test-local.log';
879
- AnsiLogger.setGlobalLogfile('test-global.log', LogLevel.DEBUG, true);
880
- logger.debug('Debug message');
881
- logger.info('Info message');
882
- logger.notice('Notice message');
883
- logger.warn('Warn message');
884
- logger.error('Error message');
885
- logger.fatal('Fatal message');
886
- const obj: object = {
887
- logName: 'TestLogger',
888
- logLevel: LogLevel.DEBUG,
889
- logWithColors: true,
890
- logTimestampFormat: TimestampFormat.TIME_MILLIS,
891
- };
892
- logger.log(LogLevel.DEBUG, `Debug message with params: ${rs}\n`, obj);
893
- logger.log(LogLevel.DEBUG, `Debug message with params: ${rs}\n`, obj, 123, 212121111111111122121n, 'Text', true, null, undefined, () => {
894
- //
895
- });
896
- logger.log(LogLevel.DEBUG, `Debug message with array params: ${rs}\n`, obj, [123, 'abc', { a: 1, b: 2 }], 123, 212121111111111122121n, 'Text', true, null, undefined, () => {
897
- //
898
- });
899
- logger.log(LogLevel.DEBUG, `Debug message without params: ${debugStringify(obj)}`);
900
- }
901
- */
902
- /*
903
-  - Reset (clear color)
904
-  - Bold
905
-  - Italic
906
-  - Underline
907
-  - Erase the line from cursor
908
-
909
-  - Black
910
-  - Red
911
-  - Green
912
-  - Yellow
913
-  - Blue
914
-  - Magenta
915
-  - Cyan
916
-  - White
917
-
918
- [90-97m - Bright
919
-
920
-  - Black background
921
-  - Red background
922
-  - Green background
923
-  - Yellow background
924
-  - Blue background
925
-  - Magenta background
926
-  - Cyan background
927
-  - White background
928
-
929
- [100-107m - Bright background
930
-
931
-  // Orange
932
-
933
- RGB foreground
934
- [38;2;<R>;<G>;<B>m
935
-
936
- RGB background
937
- [48;2;<R>;<G>;<B>m
938
-
939
- 256 colors foreground
940
- [38;5;<FG COLOR>m
941
-
942
- 256 colors background
943
- [48;5;<BG COLOR>m
944
- */
945
- //# sourceMappingURL=logger.js.map