@feizk/logger 1.4.0 → 1.5.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/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # @feizk/logger
2
2
 
3
+ ## 1.5.0
4
+
5
+ ### Minor Changes
6
+
7
+ - f3f8525: - Renamed `timestampFormat` to `formatTimestamp` and changed it to always be a function returning `[TimestampType, string]`
8
+ - Renamed `logFormat` to `formatLog`
9
+ - Renamed `logLevel` to `level`
10
+ - Renamed `setLogLevel` method to `setLevel`
11
+ - Added `TimestampTypes` interface and `TimestampType` union type for type safety
12
+ - Exported `TIMESTAMP_TYPES` constant and new types from the package index
13
+ - Updated `LoggerOptions` interface with new option names and types
14
+ - Modified `formatTimestamp` utility function to accept and call the user-provided function
15
+ - Updated all test cases to use the new option formats
16
+ - Updated README.md documentation, examples, and API reference
17
+
3
18
  ## 1.4.0
4
19
 
5
20
  ### Minor Changes
package/README.md CHANGED
@@ -27,10 +27,10 @@ Customize the logger with constructor options:
27
27
 
28
28
  ```typescript
29
29
  const logger = new Logger({
30
- enableColors: true, // Default: true
31
- timestampFormat: 'iso', // 'iso' | 'locale' | custom function, Default: 'iso'
32
- logFormat: undefined, // Custom formatter function, Default: undefined
33
- logLevel: 'debug', // 'debug' | 'info' | 'warn' | 'error', Default: 'debug'
30
+ enableColors: true, // Default: true
31
+ formatTimestamp: undefined, // Custom timestamp formatter function, Default: ISO format
32
+ formatLog: undefined, // Custom log formatter function, Default: undefined
33
+ level: 'debug', // 'debug' | 'info' | 'warn' | 'error', Default: 'debug'
34
34
  });
35
35
  ```
36
36
 
@@ -41,15 +41,22 @@ const logger = new Logger({
41
41
  const noColorLogger = new Logger({ enableColors: false });
42
42
 
43
43
  // Use locale timestamp
44
- const localeLogger = new Logger({ timestampFormat: 'locale' });
44
+ const localeLogger = new Logger({
45
+ formatTimestamp: (types) => [types.Locale, new Date().toLocaleString()],
46
+ });
47
+
48
+ // Custom timestamp
49
+ const customLogger = new Logger({
50
+ formatTimestamp: () => [TIMESTAMP_TYPES.Custom, 'custom-time'],
51
+ });
45
52
 
46
53
  // Filter logs below info level
47
- const infoLogger = new Logger({ logLevel: 'info' });
54
+ const infoLogger = new Logger({ level: 'info' });
48
55
  infoLogger.debug('Not logged');
49
56
  infoLogger.info('Logged'); // and higher
50
57
 
51
58
  // Change level dynamically
52
- logger.setLogLevel('error');
59
+ logger.setLevel('error');
53
60
  ```
54
61
 
55
62
  ## API
@@ -60,6 +67,6 @@ logger.setLogLevel('error');
60
67
  - `warn(...args: unknown[])`: Logs a warning message.
61
68
  - `error(...args: unknown[])`: Logs an error message.
62
69
  - `debug(...args: unknown[])`: Logs a debug message.
63
- - `setLogLevel(level: LogLevel)`: Sets the minimum log level for filtering messages.
70
+ - `setLevel(level: LogLevel)`: Sets the minimum log level for filtering messages.
64
71
 
65
72
  All messages include a timestamp and are colored accordingly (unless disabled via options).
package/dist/index.d.mts CHANGED
@@ -1,9 +1,15 @@
1
1
  type LogLevel = 'debug' | 'info' | 'warn' | 'error';
2
+ type TimestampType = 'iso' | 'locale' | 'custom';
3
+ interface TimestampTypes {
4
+ ISO: 'iso';
5
+ Locale: 'locale';
6
+ Custom: 'custom';
7
+ }
2
8
  interface LoggerOptions {
3
9
  enableColors?: boolean;
4
- timestampFormat?: 'iso' | 'locale' | ((date: Date) => string);
5
- logFormat?: (level: string, timestamp: string, args: unknown[]) => string;
6
- logLevel?: LogLevel;
10
+ formatTimestamp?: (types: TimestampTypes, date?: Date) => [TimestampType, string];
11
+ formatLog?: (level: string, timestamp: string, args: unknown[]) => string;
12
+ level?: LogLevel;
7
13
  }
8
14
 
9
15
  /**
@@ -11,13 +17,13 @@ interface LoggerOptions {
11
17
  */
12
18
  declare class Logger {
13
19
  private options;
14
- private logLevel;
20
+ private level;
15
21
  constructor(options?: LoggerOptions);
16
22
  /**
17
23
  * Sets the minimum log level for filtering messages.
18
24
  * @param level - The log level to set.
19
25
  */
20
- setLogLevel(level: LogLevel): void;
26
+ setLevel(level: LogLevel): void;
21
27
  /**
22
28
  * Checks if a log level should be output based on the current log level.
23
29
  * @param level - The log level to check.
@@ -46,4 +52,6 @@ declare class Logger {
46
52
  debug(...args: unknown[]): void;
47
53
  }
48
54
 
49
- export { type LogLevel, Logger, type LoggerOptions };
55
+ declare const TIMESTAMP_TYPES: TimestampTypes;
56
+
57
+ export { type LogLevel, Logger, type LoggerOptions, TIMESTAMP_TYPES, type TimestampType, type TimestampTypes };
package/dist/index.d.ts CHANGED
@@ -1,9 +1,15 @@
1
1
  type LogLevel = 'debug' | 'info' | 'warn' | 'error';
2
+ type TimestampType = 'iso' | 'locale' | 'custom';
3
+ interface TimestampTypes {
4
+ ISO: 'iso';
5
+ Locale: 'locale';
6
+ Custom: 'custom';
7
+ }
2
8
  interface LoggerOptions {
3
9
  enableColors?: boolean;
4
- timestampFormat?: 'iso' | 'locale' | ((date: Date) => string);
5
- logFormat?: (level: string, timestamp: string, args: unknown[]) => string;
6
- logLevel?: LogLevel;
10
+ formatTimestamp?: (types: TimestampTypes, date?: Date) => [TimestampType, string];
11
+ formatLog?: (level: string, timestamp: string, args: unknown[]) => string;
12
+ level?: LogLevel;
7
13
  }
8
14
 
9
15
  /**
@@ -11,13 +17,13 @@ interface LoggerOptions {
11
17
  */
12
18
  declare class Logger {
13
19
  private options;
14
- private logLevel;
20
+ private level;
15
21
  constructor(options?: LoggerOptions);
16
22
  /**
17
23
  * Sets the minimum log level for filtering messages.
18
24
  * @param level - The log level to set.
19
25
  */
20
- setLogLevel(level: LogLevel): void;
26
+ setLevel(level: LogLevel): void;
21
27
  /**
22
28
  * Checks if a log level should be output based on the current log level.
23
29
  * @param level - The log level to check.
@@ -46,4 +52,6 @@ declare class Logger {
46
52
  debug(...args: unknown[]): void;
47
53
  }
48
54
 
49
- export { type LogLevel, Logger, type LoggerOptions };
55
+ declare const TIMESTAMP_TYPES: TimestampTypes;
56
+
57
+ export { type LogLevel, Logger, type LoggerOptions, TIMESTAMP_TYPES, type TimestampType, type TimestampTypes };
package/dist/index.js CHANGED
@@ -30,24 +30,21 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
- Logger: () => Logger
33
+ Logger: () => Logger,
34
+ TIMESTAMP_TYPES: () => TIMESTAMP_TYPES
34
35
  });
35
36
  module.exports = __toCommonJS(index_exports);
36
37
 
37
38
  // src/utils.ts
38
39
  var import_chalk = __toESM(require("chalk"));
39
- function formatTimestamp(options, date = /* @__PURE__ */ new Date()) {
40
- const { timestampFormat = "iso" } = options;
41
- if (typeof timestampFormat === "function") {
42
- return timestampFormat(date);
43
- }
44
- switch (timestampFormat) {
45
- case "locale":
46
- return date.toLocaleString();
47
- case "iso":
48
- default:
49
- return date.toISOString();
50
- }
40
+ var TIMESTAMP_TYPES = {
41
+ ISO: "iso",
42
+ Locale: "locale",
43
+ Custom: "custom"
44
+ };
45
+ function formatTimestamp(formatTimestampFn, types, date = /* @__PURE__ */ new Date()) {
46
+ const [, timestamp] = formatTimestampFn(types, date);
47
+ return timestamp;
51
48
  }
52
49
  function getColor(level, enableColors) {
53
50
  if (!enableColors) return level;
@@ -60,15 +57,16 @@ function getColor(level, enableColors) {
60
57
  return colors[level] || level;
61
58
  }
62
59
  function formatLog(level, timestamp, args, options) {
63
- const { logFormat, enableColors = true } = options;
60
+ const { formatLog: formatLog2, enableColors = true } = options;
64
61
  const coloredLevel = getColor(level, enableColors);
65
- if (logFormat) {
66
- return [logFormat(coloredLevel, timestamp, args)];
62
+ if (formatLog2) {
63
+ return [formatLog2(coloredLevel, timestamp, args)];
67
64
  }
68
65
  return [`${coloredLevel} ${timestamp}`, ...args];
69
66
  }
70
67
 
71
68
  // src/logger.ts
69
+ var defaultFormatTimestamp = (types, date = /* @__PURE__ */ new Date()) => [types.ISO, date.toISOString()];
72
70
  var LOG_LEVEL_PRIORITIES = {
73
71
  debug: 0,
74
72
  info: 1,
@@ -79,17 +77,17 @@ var Logger = class {
79
77
  constructor(options = {}) {
80
78
  this.options = {
81
79
  enableColors: options.enableColors ?? true,
82
- timestampFormat: options.timestampFormat ?? "iso",
83
- logFormat: options.logFormat
80
+ formatTimestamp: options.formatTimestamp ?? defaultFormatTimestamp,
81
+ formatLog: options.formatLog
84
82
  };
85
- this.logLevel = options.logLevel ?? "debug";
83
+ this.level = options.level ?? "debug";
86
84
  }
87
85
  /**
88
86
  * Sets the minimum log level for filtering messages.
89
87
  * @param level - The log level to set.
90
88
  */
91
- setLogLevel(level) {
92
- this.logLevel = level;
89
+ setLevel(level) {
90
+ this.level = level;
93
91
  }
94
92
  /**
95
93
  * Checks if a log level should be output based on the current log level.
@@ -97,7 +95,7 @@ var Logger = class {
97
95
  * @returns True if the message should be logged.
98
96
  */
99
97
  shouldLog(level) {
100
- return LOG_LEVEL_PRIORITIES[level] >= LOG_LEVEL_PRIORITIES[this.logLevel];
98
+ return LOG_LEVEL_PRIORITIES[level] >= LOG_LEVEL_PRIORITIES[this.level];
101
99
  }
102
100
  /**
103
101
  * Logs an info message.
@@ -105,7 +103,10 @@ var Logger = class {
105
103
  */
106
104
  info(...args) {
107
105
  if (!this.shouldLog("info")) return;
108
- const timestamp = formatTimestamp(this.options);
106
+ const timestamp = formatTimestamp(
107
+ this.options.formatTimestamp,
108
+ TIMESTAMP_TYPES
109
+ );
109
110
  console.log(...formatLog("[INFO]", timestamp, args, this.options));
110
111
  }
111
112
  /**
@@ -114,7 +115,10 @@ var Logger = class {
114
115
  */
115
116
  warn(...args) {
116
117
  if (!this.shouldLog("warn")) return;
117
- const timestamp = formatTimestamp(this.options);
118
+ const timestamp = formatTimestamp(
119
+ this.options.formatTimestamp,
120
+ TIMESTAMP_TYPES
121
+ );
118
122
  console.log(...formatLog("[WARN]", timestamp, args, this.options));
119
123
  }
120
124
  /**
@@ -123,7 +127,10 @@ var Logger = class {
123
127
  */
124
128
  error(...args) {
125
129
  if (!this.shouldLog("error")) return;
126
- const timestamp = formatTimestamp(this.options);
130
+ const timestamp = formatTimestamp(
131
+ this.options.formatTimestamp,
132
+ TIMESTAMP_TYPES
133
+ );
127
134
  console.log(...formatLog("[ERROR]", timestamp, args, this.options));
128
135
  }
129
136
  /**
@@ -132,12 +139,16 @@ var Logger = class {
132
139
  */
133
140
  debug(...args) {
134
141
  if (!this.shouldLog("debug")) return;
135
- const timestamp = formatTimestamp(this.options);
142
+ const timestamp = formatTimestamp(
143
+ this.options.formatTimestamp,
144
+ TIMESTAMP_TYPES
145
+ );
136
146
  console.log(...formatLog("[DEBUG]", timestamp, args, this.options));
137
147
  }
138
148
  };
139
149
  // Annotate the CommonJS export names for ESM import in node:
140
150
  0 && (module.exports = {
141
- Logger
151
+ Logger,
152
+ TIMESTAMP_TYPES
142
153
  });
143
154
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/utils.ts","../src/logger.ts"],"sourcesContent":["export { Logger } from './logger';\nexport type { LoggerOptions, LogLevel } from './types';\n","import chalk from 'chalk';\nimport type { LoggerOptions } from './types';\n\nexport function formatTimestamp(\n options: LoggerOptions,\n date: Date = new Date(),\n): string {\n const { timestampFormat = 'iso' } = options;\n if (typeof timestampFormat === 'function') {\n return timestampFormat(date);\n }\n switch (timestampFormat) {\n case 'locale':\n return date.toLocaleString();\n case 'iso':\n default:\n return date.toISOString();\n }\n}\n\nexport function getColor(level: string, enableColors: boolean): string {\n if (!enableColors) return level;\n const colors: Record<string, string> = {\n '[INFO]': chalk.blue(level),\n '[WARN]': chalk.yellow(level),\n '[ERROR]': chalk.red(level),\n '[DEBUG]': chalk.gray(level),\n };\n return colors[level] || level;\n}\n\nexport function formatLog(\n level: string,\n timestamp: string,\n args: unknown[],\n options: LoggerOptions,\n): [string, ...unknown[]] {\n const { logFormat, enableColors = true } = options;\n const coloredLevel = getColor(level, enableColors);\n if (logFormat) {\n return [logFormat(coloredLevel, timestamp, args)];\n }\n return [`${coloredLevel} ${timestamp}`, ...args];\n}\n","import type { LoggerOptions, LogLevel } from './types';\nimport { formatTimestamp, formatLog } from './utils';\n\nconst LOG_LEVEL_PRIORITIES: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n};\n\n/**\n * A simple logger with colored outputs and timestamps.\n */\nexport class Logger {\n private options: LoggerOptions;\n private logLevel: LogLevel;\n\n constructor(options: LoggerOptions = {}) {\n this.options = {\n enableColors: options.enableColors ?? true,\n timestampFormat: options.timestampFormat ?? 'iso',\n logFormat: options.logFormat,\n };\n this.logLevel = options.logLevel ?? 'debug';\n }\n\n /**\n * Sets the minimum log level for filtering messages.\n * @param level - The log level to set.\n */\n setLogLevel(level: LogLevel): void {\n this.logLevel = level;\n }\n\n /**\n * Checks if a log level should be output based on the current log level.\n * @param level - The log level to check.\n * @returns True if the message should be logged.\n */\n private shouldLog(level: LogLevel): boolean {\n return LOG_LEVEL_PRIORITIES[level] >= LOG_LEVEL_PRIORITIES[this.logLevel];\n }\n\n /**\n * Logs an info message.\n * @param args - The arguments to log.\n */\n info(...args: unknown[]): void {\n if (!this.shouldLog('info')) return;\n const timestamp = formatTimestamp(this.options);\n console.log(...formatLog('[INFO]', timestamp, args, this.options));\n }\n\n /**\n * Logs a warning message.\n * @param args - The arguments to log.\n */\n warn(...args: unknown[]): void {\n if (!this.shouldLog('warn')) return;\n const timestamp = formatTimestamp(this.options);\n console.log(...formatLog('[WARN]', timestamp, args, this.options));\n }\n\n /**\n * Logs an error message.\n * @param args - The arguments to log.\n */\n error(...args: unknown[]): void {\n if (!this.shouldLog('error')) return;\n const timestamp = formatTimestamp(this.options);\n console.log(...formatLog('[ERROR]', timestamp, args, this.options));\n }\n\n /**\n * Logs a debug message.\n * @param args - The arguments to log.\n */\n debug(...args: unknown[]): void {\n if (!this.shouldLog('debug')) return;\n const timestamp = formatTimestamp(this.options);\n console.log(...formatLog('[DEBUG]', timestamp,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} from './utils';\nexport type {\n LoggerOptions,\n LogLevel,\n TimestampTypes,\n TimestampType,\n} from './types';\n","import chalk from 'chalk';\nimport type { LoggerOptions, TimestampTypes } from './types';\n\nexport const TIMESTAMP_TYPES: TimestampTypes = {\n ISO: 'iso',\n Locale: 'locale',\n Custom: 'custom',\n};\n\nexport function formatTimestamp(\n formatTimestampFn: NonNullable<LoggerOptions['formatTimestamp']>,\n types: TimestampTypes,\n date: Date = new Date(),\n): string {\n const [, timestamp] = formatTimestampFn(types, date);\n return timestamp;\n}\n\nexport function getColor(level: string, enableColors: boolean): string {\n if (!enableColors) return level;\n const colors: Record<string, string> = {\n '[INFO]': chalk.blue(level),\n '[WARN]': chalk.yellow(level),\n '[ERROR]': chalk.red(level),\n '[DEBUG]': chalk.gray(level),\n };\n return colors[level] || level;\n}\n\nexport function formatLog(\n level: string,\n timestamp: string,\n args: unknown[],\n options: LoggerOptions,\n): [string, ...unknown[]] {\n const { formatLog, enableColors = true } = options;\n const coloredLevel = getColor(level, enableColors);\n if (formatLog) {\n return [formatLog(coloredLevel, timestamp, args)];\n }\n return [`${coloredLevel} ${timestamp}`, ...args];\n}\n","import type { LoggerOptions, LogLevel, TimestampTypes } from './types';\nimport { formatTimestamp, formatLog, TIMESTAMP_TYPES } from './utils';\n\nimport type { TimestampType } from './types';\n\nconst defaultFormatTimestamp = (\n types: TimestampTypes,\n date: Date = new Date(),\n): [TimestampType, string] => [types.ISO, date.toISOString()];\n\nconst LOG_LEVEL_PRIORITIES: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n};\n\n/**\n * A simple logger with colored outputs and timestamps.\n */\nexport class Logger {\n private options: LoggerOptions;\n private level: LogLevel;\n\n constructor(options: LoggerOptions = {}) {\n this.options = {\n enableColors: options.enableColors ?? true,\n formatTimestamp: options.formatTimestamp ?? defaultFormatTimestamp,\n formatLog: options.formatLog,\n };\n this.level = options.level ?? 'debug';\n }\n\n /**\n * Sets the minimum log level for filtering messages.\n * @param level - The log level to set.\n */\n setLevel(level: LogLevel): void {\n this.level = level;\n }\n\n /**\n * Checks if a log level should be output based on the current log level.\n * @param level - The log level to check.\n * @returns True if the message should be logged.\n */\n private shouldLog(level: LogLevel): boolean {\n return LOG_LEVEL_PRIORITIES[level] >= LOG_LEVEL_PRIORITIES[this.level];\n }\n\n /**\n * Logs an info message.\n * @param args - The arguments to log.\n */\n info(...args: unknown[]): void {\n if (!this.shouldLog('info')) return;\n const timestamp = formatTimestamp(\n this.options.formatTimestamp!,\n TIMESTAMP_TYPES,\n );\n console.log(...formatLog('[INFO]', timestamp, args, this.options));\n }\n\n /**\n * Logs a warning message.\n * @param args - The arguments to log.\n */\n warn(...args: unknown[]): void {\n if (!this.shouldLog('warn')) return;\n const timestamp = formatTimestamp(\n this.options.formatTimestamp!,\n TIMESTAMP_TYPES,\n );\n console.log(...formatLog('[WARN]', timestamp, args, this.options));\n }\n\n /**\n * Logs an error message.\n * @param args - The arguments to log.\n */\n error(...args: unknown[]): void {\n if (!this.shouldLog('error')) return;\n const timestamp = formatTimestamp(\n this.options.formatTimestamp!,\n TIMESTAMP_TYPES,\n );\n console.log(...formatLog('[ERROR]', timestamp, args, this.options));\n }\n\n /**\n * Logs a debug message.\n * @param args - The arguments to log.\n */\n debug(...args: unknown[]): void {\n if (!this.shouldLog('debug')) return;\n const timestamp = formatTimestamp(\n this.options.formatTimestamp!,\n TIMESTAMP_TYPES,\n );\n console.log(...formatLog('[DEBUG]', timestamp, args, this.options));\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,mBAAkB;AAGX,IAAM,kBAAkC;AAAA,EAC7C,KAAK;AAAA,EACL,QAAQ;AAAA,EACR,QAAQ;AACV;AAEO,SAAS,gBACd,mBACA,OACA,OAAa,oBAAI,KAAK,GACd;AACR,QAAM,CAAC,EAAE,SAAS,IAAI,kBAAkB,OAAO,IAAI;AACnD,SAAO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AAA,EAMA,QAAQ,MAAuB;AAC7B,QAAI,CAAC,KAAK,UAAU,MAAM,EAAG;AAC7B,UAAM,YAAY;AAAA,MAChB,KAAK,QAAQ;AAAA,MACb;AAAA,IACF;AACA,YAAQ,IAAI,GAAG,UAAU,UAAU,WAAW,MAAM,KAAK,OAAO,CAAC;AAAA,EACnE;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,QAAQ,MAAuB;AAC7B,QAAI,CAAC,KAAK,UAAU,MAAM,EAAG;AAC7B,UAAM,YAAY;AAAA,MAChB,KAAK,QAAQ;AAAA,MACb;AAAA,IACF;AACA,YAAQ,IAAI,GAAG,UAAU,UAAU,WAAW,MAAM,KAAK,OAAO,CAAC;AAAA,EACnE;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,SAAS,MAAuB;AAC9B,QAAI,CAAC,KAAK,UAAU,OAAO,EAAG;AAC9B,UAAM,YAAY;AAAA,MAChB,KAAK,QAAQ;AAAA,MACb;AAAA,IACF;AACA,YAAQ,IAAI,GAAG,UAAU,WAAW,WAAW,MAAM,KAAK,OAAO,CAAC;AAAA,EACpE;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,SAAS,MAAuB;AAC9B,QAAI,CAAC,KAAK,UAAU,OAAO,EAAG;AAC9B,UAAM,YAAY;AAAA,MAChB,KAAK,QAAQ;AAAA,MACb;AAAA,IACF;AACA,YAAQ,IAAI,GAAG,UAAU,WAAW,WAAW,MAAM,KAAK,OAAO,CAAC;AAAA,EACpE;AACF;","names":["chalk","formatLog"]}
package/dist/index.mjs CHANGED
@@ -1,17 +1,13 @@
1
1
  // src/utils.ts
2
2
  import chalk from "chalk";
3
- function formatTimestamp(options, date = /* @__PURE__ */ new Date()) {
4
- const { timestampFormat = "iso" } = options;
5
- if (typeof timestampFormat === "function") {
6
- return timestampFormat(date);
7
- }
8
- switch (timestampFormat) {
9
- case "locale":
10
- return date.toLocaleString();
11
- case "iso":
12
- default:
13
- return date.toISOString();
14
- }
3
+ var TIMESTAMP_TYPES = {
4
+ ISO: "iso",
5
+ Locale: "locale",
6
+ Custom: "custom"
7
+ };
8
+ function formatTimestamp(formatTimestampFn, types, date = /* @__PURE__ */ new Date()) {
9
+ const [, timestamp] = formatTimestampFn(types, date);
10
+ return timestamp;
15
11
  }
16
12
  function getColor(level, enableColors) {
17
13
  if (!enableColors) return level;
@@ -24,15 +20,16 @@ function getColor(level, enableColors) {
24
20
  return colors[level] || level;
25
21
  }
26
22
  function formatLog(level, timestamp, args, options) {
27
- const { logFormat, enableColors = true } = options;
23
+ const { formatLog: formatLog2, enableColors = true } = options;
28
24
  const coloredLevel = getColor(level, enableColors);
29
- if (logFormat) {
30
- return [logFormat(coloredLevel, timestamp, args)];
25
+ if (formatLog2) {
26
+ return [formatLog2(coloredLevel, timestamp, args)];
31
27
  }
32
28
  return [`${coloredLevel} ${timestamp}`, ...args];
33
29
  }
34
30
 
35
31
  // src/logger.ts
32
+ var defaultFormatTimestamp = (types, date = /* @__PURE__ */ new Date()) => [types.ISO, date.toISOString()];
36
33
  var LOG_LEVEL_PRIORITIES = {
37
34
  debug: 0,
38
35
  info: 1,
@@ -43,17 +40,17 @@ var Logger = class {
43
40
  constructor(options = {}) {
44
41
  this.options = {
45
42
  enableColors: options.enableColors ?? true,
46
- timestampFormat: options.timestampFormat ?? "iso",
47
- logFormat: options.logFormat
43
+ formatTimestamp: options.formatTimestamp ?? defaultFormatTimestamp,
44
+ formatLog: options.formatLog
48
45
  };
49
- this.logLevel = options.logLevel ?? "debug";
46
+ this.level = options.level ?? "debug";
50
47
  }
51
48
  /**
52
49
  * Sets the minimum log level for filtering messages.
53
50
  * @param level - The log level to set.
54
51
  */
55
- setLogLevel(level) {
56
- this.logLevel = level;
52
+ setLevel(level) {
53
+ this.level = level;
57
54
  }
58
55
  /**
59
56
  * Checks if a log level should be output based on the current log level.
@@ -61,7 +58,7 @@ var Logger = class {
61
58
  * @returns True if the message should be logged.
62
59
  */
63
60
  shouldLog(level) {
64
- return LOG_LEVEL_PRIORITIES[level] >= LOG_LEVEL_PRIORITIES[this.logLevel];
61
+ return LOG_LEVEL_PRIORITIES[level] >= LOG_LEVEL_PRIORITIES[this.level];
65
62
  }
66
63
  /**
67
64
  * Logs an info message.
@@ -69,7 +66,10 @@ var Logger = class {
69
66
  */
70
67
  info(...args) {
71
68
  if (!this.shouldLog("info")) return;
72
- const timestamp = formatTimestamp(this.options);
69
+ const timestamp = formatTimestamp(
70
+ this.options.formatTimestamp,
71
+ TIMESTAMP_TYPES
72
+ );
73
73
  console.log(...formatLog("[INFO]", timestamp, args, this.options));
74
74
  }
75
75
  /**
@@ -78,7 +78,10 @@ var Logger = class {
78
78
  */
79
79
  warn(...args) {
80
80
  if (!this.shouldLog("warn")) return;
81
- const timestamp = formatTimestamp(this.options);
81
+ const timestamp = formatTimestamp(
82
+ this.options.formatTimestamp,
83
+ TIMESTAMP_TYPES
84
+ );
82
85
  console.log(...formatLog("[WARN]", timestamp, args, this.options));
83
86
  }
84
87
  /**
@@ -87,7 +90,10 @@ var Logger = class {
87
90
  */
88
91
  error(...args) {
89
92
  if (!this.shouldLog("error")) return;
90
- const timestamp = formatTimestamp(this.options);
93
+ const timestamp = formatTimestamp(
94
+ this.options.formatTimestamp,
95
+ TIMESTAMP_TYPES
96
+ );
91
97
  console.log(...formatLog("[ERROR]", timestamp, args, this.options));
92
98
  }
93
99
  /**
@@ -96,11 +102,15 @@ var Logger = class {
96
102
  */
97
103
  debug(...args) {
98
104
  if (!this.shouldLog("debug")) return;
99
- const timestamp = formatTimestamp(this.options);
105
+ const timestamp = formatTimestamp(
106
+ this.options.formatTimestamp,
107
+ TIMESTAMP_TYPES
108
+ );
100
109
  console.log(...formatLog("[DEBUG]", timestamp, args, this.options));
101
110
  }
102
111
  };
103
112
  export {
104
- Logger
113
+ Logger,
114
+ TIMESTAMP_TYPES
105
115
  };
106
116
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/utils.ts","../src/logger.ts"],"sourcesContent":["import chalk from 'chalk';\nimport type { LoggerOptions } from './types';\n\nexport function formatTimestamp(\n options: LoggerOptions,\n date: Date = new Date(),\n): string {\n const { timestampFormat = 'iso' } = options;\n if (typeof timestampFormat === 'function') {\n return timestampFormat(date);\n }\n switch (timestampFormat) {\n case 'locale':\n return date.toLocaleString();\n case 'iso':\n default:\n return date.toISOString();\n }\n}\n\nexport function getColor(level: string, enableColors: boolean): string {\n if (!enableColors) return level;\n const colors: Record<string, string> = {\n '[INFO]': chalk.blue(level),\n '[WARN]': chalk.yellow(level),\n '[ERROR]': chalk.red(level),\n '[DEBUG]': chalk.gray(level),\n };\n return colors[level] || level;\n}\n\nexport function formatLog(\n level: string,\n timestamp: string,\n args: unknown[],\n options: LoggerOptions,\n): [string, ...unknown[]] {\n const { logFormat, enableColors = true } = options;\n const coloredLevel = getColor(level, enableColors);\n if (logFormat) {\n return [logFormat(coloredLevel, timestamp, args)];\n }\n return [`${coloredLevel} ${timestamp}`, ...args];\n}\n","import type { LoggerOptions, LogLevel } from './types';\nimport { formatTimestamp, formatLog } from './utils';\n\nconst LOG_LEVEL_PRIORITIES: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n};\n\n/**\n * A simple logger with colored outputs and timestamps.\n */\nexport class Logger {\n private options: LoggerOptions;\n private logLevel: LogLevel;\n\n constructor(options: LoggerOptions = {}) {\n this.options = {\n enableColors: options.enableColors ?? true,\n timestampFormat: options.timestampFormat ?? 'iso',\n logFormat: options.logFormat,\n };\n this.logLevel = options.logLevel ?? 'debug';\n }\n\n /**\n * Sets the minimum log level for filtering messages.\n * @param level - The log level to set.\n */\n setLogLevel(level: LogLevel): void {\n this.logLevel = level;\n }\n\n /**\n * Checks if a log level should be output based on the current log level.\n * @param level - The log level to check.\n * @returns True if the message should be logged.\n */\n private shouldLog(level: LogLevel): boolean {\n return LOG_LEVEL_PRIORITIES[level] >= LOG_LEVEL_PRIORITIES[this.logLevel];\n }\n\n /**\n * Logs an info message.\n * @param args - The arguments to log.\n */\n info(...args: unknown[]): void {\n if (!this.shouldLog('info')) return;\n const timestamp = formatTimestamp(this.options);\n console.log(...formatLog('[INFO]', timestamp, args, this.options));\n }\n\n /**\n * Logs a warning message.\n * @param args - The arguments to log.\n */\n warn(...args: unknown[]): void {\n if (!this.shouldLog('warn')) return;\n const timestamp = formatTimestamp(this.options);\n console.log(...formatLog('[WARN]', timestamp, args, this.options));\n }\n\n /**\n * Logs an error message.\n * @param args - The arguments to log.\n */\n error(...args: unknown[]): void {\n if (!this.shouldLog('error')) return;\n const timestamp = formatTimestamp(this.options);\n console.log(...formatLog('[ERROR]', timestamp, args, this.options));\n }\n\n /**\n * Logs a debug message.\n * @param args - The arguments to log.\n */\n debug(...args: unknown[]): void {\n if (!this.shouldLog('debug')) return;\n const timestamp = formatTimestamp(this.options);\n console.log(...formatLog('[DEBUG]', timestamp, args, this.options));\n }\n}\n"],"mappings":";AAAA,OAAO,WAAW;AAGX,SAAS,gBACd,SACA,OAAa,oBAAI,KAAK,GACd;AACR,QAAM,EAAE,kBAAkB,MAAM,IAAI;AACpC,MAAI,OAAO,oBAAoB,YAAY;AACzC,WAAO,gBAAgB,IAAI;AAAA,EAC7B;AACA,UAAQ,iBAAiB;AAAA,IACvB,KAAK;AACH,aAAO,KAAK,eAAe;AAAA,IAC7B,KAAK;AAAA,IACL;AACE,aAAO,KAAK,YAAY;AAAA,EAC5B;AACF;AAEO,SAAS,SAAS,OAAe,cAA+B;AACrE,MAAI,CAAC,aAAc,QAAO;AAC1B,QAAM,SAAiC;AAAA,IACrC,UAAU,MAAM,KAAK,KAAK;AAAA,IAC1B,UAAU,MAAM,OAAO,KAAK;AAAA,IAC5B,WAAW,MAAM,IAAI,KAAK;AAAA,IAC1B,WAAW,MAAM,KAAK,KAAK;AAAA,EAC7B;AACA,SAAO,OAAO,KAAK,KAAK;AAC1B;AAEO,SAAS,UACd,OACA,WACA,MACA,SACwB;AACxB,QAAM,EAAE,WAAW,e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AAU,OAAO,EAAG;AAC9B,UAAM,YAAY,gBAAgB,KAAK,OAAO;AAC9C,YAAQ,IAAI,GAAG,UAAU,WAAW,WAAW,MAAM,KAAK,OAAO,CAAC;AAAA,EACpE;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,SAAS,MAAuB;AAC9B,QAAI,CAAC,KAAK,UAAU,OAAO,EAAG;AAC9B,UAAM,YAAY,gBAAgB,KAAK,OAAO;AAC9C,YAAQ,IAAI,GAAG,UAAU,WAAW,WAAW,MAAM,KAAK,OAAO,CAAC;AAAA,EACpE;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/utils.ts","../src/logger.ts"],"sourcesContent":["import chalk from 'chalk';\nimport type { LoggerOptions, TimestampTypes } from './types';\n\nexport const TIMESTAMP_TYPES: TimestampTypes = {\n ISO: 'iso',\n Locale: 'locale',\n Custom: 'custom',\n};\n\nexport function formatTimestamp(\n formatTimestampFn: NonNullable<LoggerOptions['formatTimestamp']>,\n types: TimestampTypes,\n date: Date = new Date(),\n): string {\n const [, timestamp] = formatTimestampFn(types, date);\n return timestamp;\n}\n\nexport function getColor(level: string, enableColors: boolean): string {\n if (!enableColors) return level;\n const colors: Record<string, string> = {\n '[INFO]': chalk.blue(level),\n '[WARN]': chalk.yellow(level),\n '[ERROR]': chalk.red(level),\n '[DEBUG]': chalk.gray(level),\n };\n return colors[level] || level;\n}\n\nexport function formatLog(\n level: string,\n timestamp: string,\n args: unknown[],\n options: LoggerOptions,\n): [string, ...unknown[]] {\n const { formatLog, enableColors = true } = options;\n const coloredLevel = getColor(level, enableColors);\n if (formatLog) {\n return [formatLog(coloredLevel, timestamp, args)];\n }\n return [`${coloredLevel} ${timestamp}`, ...args];\n}\n","import type { LoggerOptions, LogLevel, TimestampTypes } from './types';\nimport { formatTimestamp, formatLog, TIMESTAMP_TYPES } from './utils';\n\nimport type { TimestampType } from './types';\n\nconst defaultFormatTimestamp = (\n types: TimestampTypes,\n date: Date = new Date(),\n): [TimestampType, string] => [types.ISO, date.toISOString()];\n\nconst LOG_LEVEL_PRIORITIES: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n};\n\n/**\n * A simple logger with colored outputs and timestamps.\n */\nexport class Logger {\n private options: LoggerOptions;\n private level: LogLevel;\n\n constructor(options: LoggerOptions = {}) {\n this.options = {\n enableColors: options.enableColors ?? true,\n formatTimestamp: options.formatTimestamp ?? defaultFormatTimestamp,\n formatLog: options.formatLog,\n };\n this.level = options.level ?? 'debug';\n }\n\n /**\n * Sets the minimum log level for filtering messages.\n * @param level - The log level to set.\n */\n setLevel(level: LogLevel): void {\n this.level = level;\n }\n\n /**\n * Checks if a log level should be output based on the current log level.\n * @param level - The log level to check.\n * @returns True if the message should be logged.\n */\n private shouldLog(level: LogLevel): boolean {\n return LOG_LEVEL_PRIORITIES[level] >= LOG_LEVEL_PRIORITIES[this.level];\n }\n\n /**\n * Logs an info message.\n * @param args - The arguments to log.\n */\n info(...args: unknown[]): void {\n if (!this.shouldLog('info')) return;\n const timestamp = formatTimestamp(\n this.options.formatTimestamp!,\n TIMESTAMP_TYPES,\n );\n console.log(...formatLog('[INFO]', timestamp, args, this.options));\n }\n\n /**\n * Logs a warning message.\n * @param args - The arguments to log.\n */\n warn(...args: unknown[]): void {\n if (!this.shouldLog('warn')) return;\n const timestamp = formatTimestamp(\n this.options.formatTimestamp!,\n TIMESTAMP_TYPES,\n );\n console.log(...formatLog('[WARN]', timestamp, args, this.options));\n }\n\n /**\n * Logs an error message.\n * @param args - The arguments to log.\n */\n error(...args: unknown[]): void {\n if (!this.shouldLog('error')) return;\n const timestamp = formatTimestamp(\n this.options.formatTimestamp!,\n TIMESTAMP_TYPES,\n );\n console.log(...formatLog('[ERROR]', timestamp, args, this.options));\n }\n\n /**\n * Logs a debug message.\n * @param args - The arguments to log.\n */\n debug(...args: unknown[]): void {\n if (!this.shouldLog('debug')) return;\n const timestamp = formatTimestamp(\n this.options.formatTimestamp!,\n TIMESTAMP_TYPES,\n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2
2
  "name": "@feizk/logger",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "description": "A simple logger package with colored outputs and timestamps",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
package/src/index.ts CHANGED
@@ -1,2 +1,8 @@
1
1
  export { Logger } from './logger';
2
- export type { LoggerOptions, LogLevel } from './types';
2
+ export { TIMESTAMP_TYPES } from './utils';
3
+ export type {
4
+ LoggerOptions,
5
+ LogLevel,
6
+ TimestampTypes,
7
+ TimestampType,
8
+ } from './types';
package/src/logger.ts CHANGED
@@ -1,5 +1,12 @@
1
- import type { LoggerOptions, LogLevel } from './types';
2
- import { formatTimestamp, formatLog } from './utils';
1
+ import type { LoggerOptions, LogLevel, TimestampTypes } from './types';
2
+ import { formatTimestamp, formatLog, TIMESTAMP_TYPES } from './utils';
3
+
4
+ import type { TimestampType } from './types';
5
+
6
+ const defaultFormatTimestamp = (
7
+ types: TimestampTypes,
8
+ date: Date = new Date(),
9
+ ): [TimestampType, string] => [types.ISO, date.toISOString()];
3
10
 
4
11
  const LOG_LEVEL_PRIORITIES: Record<LogLevel, number> = {
5
12
  debug: 0,
@@ -13,23 +20,23 @@ const LOG_LEVEL_PRIORITIES: Record<LogLevel, number> = {
13
20
  */
14
21
  export class Logger {
15
22
  private options: LoggerOptions;
16
- private logLevel: LogLevel;
23
+ private level: LogLevel;
17
24
 
18
25
  constructor(options: LoggerOptions = {}) {
19
26
  this.options = {
20
27
  enableColors: options.enableColors ?? true,
21
- timestampFormat: options.timestampFormat ?? 'iso',
22
- logFormat: options.logFormat,
28
+ formatTimestamp: options.formatTimestamp ?? defaultFormatTimestamp,
29
+ formatLog: options.formatLog,
23
30
  };
24
- this.logLevel = options.logLevel ?? 'debug';
31
+ this.level = options.level ?? 'debug';
25
32
  }
26
33
 
27
34
  /**
28
35
  * Sets the minimum log level for filtering messages.
29
36
  * @param level - The log level to set.
30
37
  */
31
- setLogLevel(level: LogLevel): void {
32
- this.logLevel = level;
38
+ setLevel(level: LogLevel): void {
39
+ this.level = level;
33
40
  }
34
41
 
35
42
  /**
@@ -38,7 +45,7 @@ export class Logger {
38
45
  * @returns True if the message should be logged.
39
46
  */
40
47
  private shouldLog(level: LogLevel): boolean {
41
- return LOG_LEVEL_PRIORITIES[level] >= LOG_LEVEL_PRIORITIES[this.logLevel];
48
+ return LOG_LEVEL_PRIORITIES[level] >= LOG_LEVEL_PRIORITIES[this.level];
42
49
  }
43
50
 
44
51
  /**
@@ -47,7 +54,10 @@ export class Logger {
47
54
  */
48
55
  info(...args: unknown[]): void {
49
56
  if (!this.shouldLog('info')) return;
50
- const timestamp = formatTimestamp(this.options);
57
+ const timestamp = formatTimestamp(
58
+ this.options.formatTimestamp!,
59
+ TIMESTAMP_TYPES,
60
+ );
51
61
  console.log(...formatLog('[INFO]', timestamp, args, this.options));
52
62
  }
53
63
 
@@ -57,7 +67,10 @@ export class Logger {
57
67
  */
58
68
  warn(...args: unknown[]): void {
59
69
  if (!this.shouldLog('warn')) return;
60
- const timestamp = formatTimestamp(this.options);
70
+ const timestamp = formatTimestamp(
71
+ this.options.formatTimestamp!,
72
+ TIMESTAMP_TYPES,
73
+ );
61
74
  console.log(...formatLog('[WARN]', timestamp, args, this.options));
62
75
  }
63
76
 
@@ -67,7 +80,10 @@ export class Logger {
67
80
  */
68
81
  error(...args: unknown[]): void {
69
82
  if (!this.shouldLog('error')) return;
70
- const timestamp = formatTimestamp(this.options);
83
+ const timestamp = formatTimestamp(
84
+ this.options.formatTimestamp!,
85
+ TIMESTAMP_TYPES,
86
+ );
71
87
  console.log(...formatLog('[ERROR]', timestamp, args, this.options));
72
88
  }
73
89
 
@@ -77,7 +93,10 @@ export class Logger {
77
93
  */
78
94
  debug(...args: unknown[]): void {
79
95
  if (!this.shouldLog('debug')) return;
80
- const timestamp = formatTimestamp(this.options);
96
+ const timestamp = formatTimestamp(
97
+ this.options.formatTimestamp!,
98
+ TIMESTAMP_TYPES,
99
+ );
81
100
  console.log(...formatLog('[DEBUG]', timestamp, args, this.options));
82
101
  }
83
102
  }
package/src/types.ts CHANGED
@@ -1,8 +1,19 @@
1
1
  export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
2
2
 
3
+ export type TimestampType = 'iso' | 'locale' | 'custom';
4
+
5
+ export interface TimestampTypes {
6
+ ISO: 'iso';
7
+ Locale: 'locale';
8
+ Custom: 'custom';
9
+ }
10
+
3
11
  export interface LoggerOptions {
4
12
  enableColors?: boolean;
5
- timestampFormat?: 'iso' | 'locale' | ((date: Date) => string);
6
- logFormat?: (level: string, timestamp: string, args: unknown[]) => string;
7
- logLevel?: LogLevel;
13
+ formatTimestamp?: (
14
+ types: TimestampTypes,
15
+ date?: Date,
16
+ ) => [TimestampType, string];
17
+ formatLog?: (level: string, timestamp: string, args: unknown[]) => string;
18
+ level?: LogLevel;
8
19
  }
package/src/utils.ts CHANGED
@@ -1,21 +1,19 @@
1
1
  import chalk from 'chalk';
2
- import type { LoggerOptions } from './types';
2
+ import type { LoggerOptions, TimestampTypes } from './types';
3
+
4
+ export const TIMESTAMP_TYPES: TimestampTypes = {
5
+ ISO: 'iso',
6
+ Locale: 'locale',
7
+ Custom: 'custom',
8
+ };
3
9
 
4
10
  export function formatTimestamp(
5
- options: LoggerOptions,
11
+ formatTimestampFn: NonNullable<LoggerOptions['formatTimestamp']>,
12
+ types: TimestampTypes,
6
13
  date: Date = new Date(),
7
14
  ): string {
8
- const { timestampFormat = 'iso' } = options;
9
- if (typeof timestampFormat === 'function') {
10
- return timestampFormat(date);
11
- }
12
- switch (timestampFormat) {
13
- case 'locale':
14
- return date.toLocaleString();
15
- case 'iso':
16
- default:
17
- return date.toISOString();
18
- }
15
+ const [, timestamp] = formatTimestampFn(types, date);
16
+ return timestamp;
19
17
  }
20
18
 
21
19
  export function getColor(level: string, enableColors: boolean): string {
@@ -35,10 +33,10 @@ export function formatLog(
35
33
  args: unknown[],
36
34
  options: LoggerOptions,
37
35
  ): [string, ...unknown[]] {
38
- const { logFormat, enableColors = true } = options;
36
+ const { formatLog, enableColors = true } = options;
39
37
  const coloredLevel = getColor(level, enableColors);
40
- if (logFormat) {
41
- return [logFormat(coloredLevel, timestamp, args)];
38
+ if (formatLog) {
39
+ return [formatLog(coloredLevel, timestamp, args)];
42
40
  }
43
41
  return [`${coloredLevel} ${timestamp}`, ...args];
44
42
  }
@@ -7,7 +7,7 @@ import {
7
7
  afterEach,
8
8
  type MockInstance,
9
9
  } from 'vitest';
10
- import { Logger } from '../src/index';
10
+ import { Logger, TIMESTAMP_TYPES } from '../src/index';
11
11
 
12
12
  describe('Logger', () => {
13
13
  let logger: Logger;
@@ -82,7 +82,9 @@ describe('Logger', () => {
82
82
  });
83
83
 
84
84
  it('should use locale timestamp format', () => {
85
- const localeLogger = new Logger({ timestampFormat: 'locale' });
85
+ const localeLogger = new Logger({
86
+ formatTimestamp: (types) => [types.Locale, new Date().toLocaleString()],
87
+ });
86
88
  localeLogger.info('test');
87
89
  const callArgs = consoleSpy.mock.calls[0][0];
88
90
  expect(callArgs).toMatch(/\d{1,2}\/\d{1,2}\/\d{4}/); // Basic locale date check
@@ -90,7 +92,7 @@ describe('Logger', () => {
90
92
 
91
93
  it('should use custom timestamp function', () => {
92
94
  const customLogger = new Logger({
93
- timestampFormat: () => 'custom-time',
95
+ formatTimestamp: () => [TIMESTAMP_TYPES.Custom, 'custom-time'],
94
96
  });
95
97
  customLogger.info('test');
96
98
  const callArgs = consoleSpy.mock.calls[0][0];
@@ -99,7 +101,7 @@ describe('Logger', () => {
99
101
 
100
102
  it('should use custom log format', () => {
101
103
  const customLogger = new Logger({
102
- logFormat: (level, timestamp, args) =>
104
+ formatLog: (level, timestamp, args) =>
103
105
  `${timestamp} ${level}: ${args.join(' ')}`,
104
106
  });
105
107
  customLogger.warn('hello', 'world');
@@ -119,7 +121,7 @@ describe('Logger', () => {
119
121
  });
120
122
 
121
123
  it('should filter logs below the set level', () => {
122
- const infoLogger = new Logger({ logLevel: 'info' });
124
+ const infoLogger = new Logger({ level: 'info' });
123
125
  infoLogger.debug('debug message');
124
126
  expect(consoleSpy).not.toHaveBeenCalled();
125
127
 
@@ -131,7 +133,7 @@ describe('Logger', () => {
131
133
  });
132
134
 
133
135
  it('should allow all levels when set to debug', () => {
134
- const debugLogger = new Logger({ logLevel: 'debug' });
136
+ const debugLogger = new Logger({ level: 'debug' });
135
137
  debugLogger.debug('debug');
136
138
  debugLogger.info('info');
137
139
  debugLogger.warn('warn');
@@ -140,7 +142,7 @@ describe('Logger', () => {
140
142
  });
141
143
 
142
144
  it('should filter debug and info when set to warn', () => {
143
- const warnLogger = new Logger({ logLevel: 'warn' });
145
+ const warnLogger = new Logger({ level: 'warn' });
144
146
  warnLogger.debug('debug');
145
147
  warnLogger.info('info');
146
148
  expect(consoleSpy).not.toHaveBeenCalled();
@@ -151,7 +153,7 @@ describe('Logger', () => {
151
153
  });
152
154
 
153
155
  it('should only log errors when set to error', () => {
154
- const errorLogger = new Logger({ logLevel: 'error' });
156
+ const errorLogger = new Logger({ level: 'error' });
155
157
  errorLogger.debug('debug');
156
158
  errorLogger.info('info');
157
159
  errorLogger.warn('warn');
@@ -166,11 +168,11 @@ describe('Logger', () => {
166
168
 
167
169
  it('should allow changing log level dynamically', () => {
168
170
  const logger = new Logger();
169
- logger.setLogLevel('error');
171
+ logger.setLevel('error');
170
172
  logger.debug('debug');
171
173
  expect(consoleSpy).not.toHaveBeenCalled();
172
174
 
173
- logger.setLogLevel('debug');
175
+ logger.setLevel('debug');
174
176
  logger.debug('debug');
175
177
  expect(consoleSpy).toHaveBeenCalledWith(
176
178
  expect.stringContaining('[DEBUG]'),