@feizk/logger 1.0.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 ADDED
@@ -0,0 +1,45 @@
1
+ # @feizk/logger
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
+
18
+ ## 1.4.0
19
+
20
+ ### Minor Changes
21
+
22
+ - 2b7b1eb: - Added `LogLevel` type ('debug' | 'info' | 'warn' | 'error') and `logLevel` option to `LoggerOptions` in `types.ts`
23
+ - Updated `logger.ts` to implement log level filtering with a `LOG_LEVEL_PRIORITIES` constant, `shouldLog` private method, and checks before each log call
24
+ - Added `setLogLevel` method to `logger.ts` for dynamic runtime level changes
25
+ - Exported `LogLevel` type from `index.ts` for external use
26
+ - Added comprehensive test cases in `logger.test.ts` for filtering behavior at different levels, dynamic level changes, and default behavior
27
+ - Updated `README.md` with `logLevel` option documentation, usage examples, and API details for the new method
28
+
29
+ ## 1.3.0
30
+
31
+ ### Minor Changes
32
+
33
+ - 6e3d7e5: - Created `src/types.ts` with `LoggerOptions` interface for `enableColors`, `timestampFormat`, and `logFormat` options\n- Created `src/utils.ts` with utility functions: `formatTimestamp`, `getColor`, and `formatLog`\n- Moved `Logger` class to `src/logger.ts` and made it configurable via constructor options with defaults\n- Updated `src/index.ts` to export `Logger` class and `LoggerOptions` type instead of containing the class\n- Removed the `success` method from `Logger` class (per user feedback)\n- Removed `[SUCCESS]` color mapping from `utils.ts`\n- Added tests in `tests/logger.test.ts` for disabling colors, locale timestamp, custom timestamp function, and custom log format\n- Removed success-related test from `tests/logger.test.ts`\n- Updated `README.md` with usage examples for new options and removed success method documentation\n- Ensured backward compatibility: existing `new Logger()` usage remains unchanged\n- All tests pass (10 tests) and build succeeds
34
+
35
+ ## 1.2.0
36
+
37
+ ### Minor Changes
38
+
39
+ - 4b70f01: Accept multiple arguments and Any type of arguments on all Logger methods
40
+
41
+ ## 1.1.0
42
+
43
+ ### Minor Changes
44
+
45
+ - ebc4e0b: Add success logging method to Logger class
package/README.md CHANGED
@@ -21,13 +21,52 @@ logger.error('This is an error');
21
21
  logger.debug('This is a debug message');
22
22
  ```
23
23
 
24
+ ### Options
25
+
26
+ Customize the logger with constructor options:
27
+
28
+ ```typescript
29
+ const logger = new Logger({
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
+ });
35
+ ```
36
+
37
+ #### Examples
38
+
39
+ ```typescript
40
+ // Disable colors
41
+ const noColorLogger = new Logger({ enableColors: false });
42
+
43
+ // Use locale timestamp
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
+ });
52
+
53
+ // Filter logs below info level
54
+ const infoLogger = new Logger({ level: 'info' });
55
+ infoLogger.debug('Not logged');
56
+ infoLogger.info('Logged'); // and higher
57
+
58
+ // Change level dynamically
59
+ logger.setLevel('error');
60
+ ```
61
+
24
62
  ## API
25
63
 
26
64
  ### Logger
27
65
 
28
- - `info(message: string)`: Logs an info message.
29
- - `warn(message: string)`: Logs a warning message.
30
- - `error(message: string)`: Logs an error message.
31
- - `debug(message: string)`: Logs a debug message.
66
+ - `info(...args: unknown[])`: Logs an info message.
67
+ - `warn(...args: unknown[])`: Logs a warning message.
68
+ - `error(...args: unknown[])`: Logs an error message.
69
+ - `debug(...args: unknown[])`: Logs a debug message.
70
+ - `setLevel(level: LogLevel)`: Sets the minimum log level for filtering messages.
32
71
 
33
- All messages include a timestamp and are colored accordingly.
72
+ All messages include a timestamp and are colored accordingly (unless disabled via options).
package/dist/index.d.mts CHANGED
@@ -1,29 +1,57 @@
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
+ }
8
+ interface LoggerOptions {
9
+ enableColors?: boolean;
10
+ formatTimestamp?: (types: TimestampTypes, date?: Date) => [TimestampType, string];
11
+ formatLog?: (level: string, timestamp: string, args: unknown[]) => string;
12
+ level?: LogLevel;
13
+ }
14
+
1
15
  /**
2
16
  * A simple logger with colored outputs and timestamps.
3
17
  */
4
18
  declare class Logger {
19
+ private options;
20
+ private level;
21
+ constructor(options?: LoggerOptions);
22
+ /**
23
+ * Sets the minimum log level for filtering messages.
24
+ * @param level - The log level to set.
25
+ */
26
+ setLevel(level: LogLevel): void;
27
+ /**
28
+ * Checks if a log level should be output based on the current log level.
29
+ * @param level - The log level to check.
30
+ * @returns True if the message should be logged.
31
+ */
32
+ private shouldLog;
5
33
  /**
6
34
  * Logs an info message.
7
- * @param message - The message to log.
35
+ * @param args - The arguments to log.
8
36
  */
9
- info(message: string): void;
37
+ info(...args: unknown[]): void;
10
38
  /**
11
39
  * Logs a warning message.
12
- * @param message - The message to log.
40
+ * @param args - The arguments to log.
13
41
  */
14
- warn(message: string): void;
42
+ warn(...args: unknown[]): void;
15
43
  /**
16
44
  * Logs an error message.
17
- * @param message - The message to log.
45
+ * @param args - The arguments to log.
18
46
  */
19
- error(message: string): void;
47
+ error(...args: unknown[]): void;
20
48
  /**
21
49
  * Logs a debug message.
22
- * @param message - The message to log.
50
+ * @param args - The arguments to log.
23
51
  */
24
- debug(message: string): void;
25
- private getTimestamp;
26
- private removeFunction;
52
+ debug(...args: unknown[]): void;
27
53
  }
28
54
 
29
- export { Logger };
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,29 +1,57 @@
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
+ }
8
+ interface LoggerOptions {
9
+ enableColors?: boolean;
10
+ formatTimestamp?: (types: TimestampTypes, date?: Date) => [TimestampType, string];
11
+ formatLog?: (level: string, timestamp: string, args: unknown[]) => string;
12
+ level?: LogLevel;
13
+ }
14
+
1
15
  /**
2
16
  * A simple logger with colored outputs and timestamps.
3
17
  */
4
18
  declare class Logger {
19
+ private options;
20
+ private level;
21
+ constructor(options?: LoggerOptions);
22
+ /**
23
+ * Sets the minimum log level for filtering messages.
24
+ * @param level - The log level to set.
25
+ */
26
+ setLevel(level: LogLevel): void;
27
+ /**
28
+ * Checks if a log level should be output based on the current log level.
29
+ * @param level - The log level to check.
30
+ * @returns True if the message should be logged.
31
+ */
32
+ private shouldLog;
5
33
  /**
6
34
  * Logs an info message.
7
- * @param message - The message to log.
35
+ * @param args - The arguments to log.
8
36
  */
9
- info(message: string): void;
37
+ info(...args: unknown[]): void;
10
38
  /**
11
39
  * Logs a warning message.
12
- * @param message - The message to log.
40
+ * @param args - The arguments to log.
13
41
  */
14
- warn(message: string): void;
42
+ warn(...args: unknown[]): void;
15
43
  /**
16
44
  * Logs an error message.
17
- * @param message - The message to log.
45
+ * @param args - The arguments to log.
18
46
  */
19
- error(message: string): void;
47
+ error(...args: unknown[]): void;
20
48
  /**
21
49
  * Logs a debug message.
22
- * @param message - The message to log.
50
+ * @param args - The arguments to log.
23
51
  */
24
- debug(message: string): void;
25
- private getTimestamp;
26
- private removeFunction;
52
+ debug(...args: unknown[]): void;
27
53
  }
28
54
 
29
- export { Logger };
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,48 +30,125 @@ 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);
37
+
38
+ // src/utils.ts
36
39
  var import_chalk = __toESM(require("chalk"));
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;
48
+ }
49
+ function getColor(level, enableColors) {
50
+ if (!enableColors) return level;
51
+ const colors = {
52
+ "[INFO]": import_chalk.default.blue(level),
53
+ "[WARN]": import_chalk.default.yellow(level),
54
+ "[ERROR]": import_chalk.default.red(level),
55
+ "[DEBUG]": import_chalk.default.gray(level)
56
+ };
57
+ return colors[level] || level;
58
+ }
59
+ function formatLog(level, timestamp, args, options) {
60
+ const { formatLog: formatLog2, enableColors = true } = options;
61
+ const coloredLevel = getColor(level, enableColors);
62
+ if (formatLog2) {
63
+ return [formatLog2(coloredLevel, timestamp, args)];
64
+ }
65
+ return [`${coloredLevel} ${timestamp}`, ...args];
66
+ }
67
+
68
+ // src/logger.ts
69
+ var defaultFormatTimestamp = (types, date = /* @__PURE__ */ new Date()) => [types.ISO, date.toISOString()];
70
+ var LOG_LEVEL_PRIORITIES = {
71
+ debug: 0,
72
+ info: 1,
73
+ warn: 2,
74
+ error: 3
75
+ };
37
76
  var Logger = class {
77
+ constructor(options = {}) {
78
+ this.options = {
79
+ enableColors: options.enableColors ?? true,
80
+ formatTimestamp: options.formatTimestamp ?? defaultFormatTimestamp,
81
+ formatLog: options.formatLog
82
+ };
83
+ this.level = options.level ?? "debug";
84
+ }
85
+ /**
86
+ * Sets the minimum log level for filtering messages.
87
+ * @param level - The log level to set.
88
+ */
89
+ setLevel(level) {
90
+ this.level = level;
91
+ }
92
+ /**
93
+ * Checks if a log level should be output based on the current log level.
94
+ * @param level - The log level to check.
95
+ * @returns True if the message should be logged.
96
+ */
97
+ shouldLog(level) {
98
+ return LOG_LEVEL_PRIORITIES[level] >= LOG_LEVEL_PRIORITIES[this.level];
99
+ }
38
100
  /**
39
101
  * Logs an info message.
40
- * @param message - The message to log.
102
+ * @param args - The arguments to log.
41
103
  */
42
- info(message) {
43
- console.log(`${import_chalk.default.blue("[INFO]")} ${this.getTimestamp()} ${message}`);
104
+ info(...args) {
105
+ if (!this.shouldLog("info")) return;
106
+ const timestamp = formatTimestamp(
107
+ this.options.formatTimestamp,
108
+ TIMESTAMP_TYPES
109
+ );
110
+ console.log(...formatLog("[INFO]", timestamp, args, this.options));
44
111
  }
45
112
  /**
46
113
  * Logs a warning message.
47
- * @param message - The message to log.
114
+ * @param args - The arguments to log.
48
115
  */
49
- warn(message) {
50
- console.log(`${import_chalk.default.yellow("[WARN]")} ${this.getTimestamp()} ${message}`);
116
+ warn(...args) {
117
+ if (!this.shouldLog("warn")) return;
118
+ const timestamp = formatTimestamp(
119
+ this.options.formatTimestamp,
120
+ TIMESTAMP_TYPES
121
+ );
122
+ console.log(...formatLog("[WARN]", timestamp, args, this.options));
51
123
  }
52
124
  /**
53
125
  * Logs an error message.
54
- * @param message - The message to log.
126
+ * @param args - The arguments to log.
55
127
  */
56
- error(message) {
57
- console.log(`${import_chalk.default.red("[ERROR]")} ${this.getTimestamp()} ${message}`);
128
+ error(...args) {
129
+ if (!this.shouldLog("error")) return;
130
+ const timestamp = formatTimestamp(
131
+ this.options.formatTimestamp,
132
+ TIMESTAMP_TYPES
133
+ );
134
+ console.log(...formatLog("[ERROR]", timestamp, args, this.options));
58
135
  }
59
136
  /**
60
137
  * Logs a debug message.
61
- * @param message - The message to log.
138
+ * @param args - The arguments to log.
62
139
  */
63
- debug(message) {
64
- console.log(`${import_chalk.default.gray("[DEBUG]")} ${this.getTimestamp()} ${message}`);
65
- }
66
- getTimestamp() {
67
- return (/* @__PURE__ */ new Date()).toISOString();
68
- }
69
- removeFunction() {
70
- return "Please remove this function";
140
+ debug(...args) {
141
+ if (!this.shouldLog("debug")) return;
142
+ const timestamp = formatTimestamp(
143
+ this.options.formatTimestamp,
144
+ TIMESTAMP_TYPES
145
+ );
146
+ console.log(...formatLog("[DEBUG]", timestamp, args, this.options));
71
147
  }
72
148
  };
73
149
  // Annotate the CommonJS export names for ESM import in node:
74
150
  0 && (module.exports = {
75
- Logger
151
+ Logger,
152
+ TIMESTAMP_TYPES
76
153
  });
77
154
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import chalk from 'chalk';\n\n/**\n * A simple logger with colored outputs and timestamps.\n */\nexport class Logger {\n /**\n * Logs an info message.\n * @param message - The message to log.\n */\n info(message: string): void {\n console.log(`${chalk.blue('[INFO]')} ${this.getTimestamp()} ${message}`);\n }\n\n /**\n * Logs a warning message.\n * @param message - The message to log.\n */\n warn(message: string): void {\n console.log(`${chalk.yellow('[WARN]')} ${this.getTimestamp()} ${message}`);\n }\n\n /**\n * Logs an error message.\n * @param message - The message to log.\n */\n error(message: string): void {\n console.log(`${chalk.red('[ERROR]')} ${this.getTimestamp()} ${message}`);\n }\n\n /**\n * Logs a debug message.\n * @param message - The message to log.\n */\n debug(message: string): void {\n console.log(`${chalk.gray('[DEBUG]')} ${this.getTimestamp()} ${message}`);\n }\n\n private getTimestamp(): string {\n return new Date().toISOString();\n }\n\n private removeFunction() {\n return 'Please remove this function';\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAkB;AAKX,IAAM,SAAN,MAAa;AAAA;AAAA;AAAA;AAAA;AAAA,EAKlB,KAAK,SAAuB;AAC1B,YAAQ,IAAI,GAAG,aAAAA,QAAM,KAAK,QAAQ,CAAC,IAAI,KAAK,aAAa,CAAC,IAAI,OAAO,EAAE;AAAA,EACzE;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,KAAK,SAAuB;AAC1B,YAAQ,IAAI,GAAG,aAAAA,QAAM,OAAO,QAAQ,CAAC,IAAI,KAAK,aAAa,CAAC,IAAI,OAAO,EAAE;AAAA,EAC3E;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,SAAuB;AAC3B,YAAQ,IAAI,GAAG,aAAAA,QAAM,IAAI,SAAS,CAAC,IAAI,KAAK,aAAa,CAAC,IAAI,OAAO,EAAE;AAAA,EACzE;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,SAAuB;AAC3B,YAAQ,IAAI,GAAG,aAAAA,QAAM,KAAK,SAAS,CAAC,IAAI,KAAK,aAAa,CAAC,IAAI,OAAO,EAAE;AAAA,EAC1E;AAAA,EAEQ,eAAuB;AAC7B,YAAO,oBAAI,KAAK,GAAE,YAAY;AAAA,EAChC;AAAA,EAEQ,iBAAiB;AACvB,WAAO;AAAA,EACT;AACF;","names":["chalk"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/utils.ts","../src/logger.ts"],"sourcesContent":["export { Logger } from './logger';\nexport { TIMESTAMP_TYPES } 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":"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","names":["chalk","formatLog"]}
package/dist/index.mjs CHANGED
@@ -1,42 +1,116 @@
1
- // src/index.ts
1
+ // src/utils.ts
2
2
  import chalk from "chalk";
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;
11
+ }
12
+ function getColor(level, enableColors) {
13
+ if (!enableColors) return level;
14
+ const colors = {
15
+ "[INFO]": chalk.blue(level),
16
+ "[WARN]": chalk.yellow(level),
17
+ "[ERROR]": chalk.red(level),
18
+ "[DEBUG]": chalk.gray(level)
19
+ };
20
+ return colors[level] || level;
21
+ }
22
+ function formatLog(level, timestamp, args, options) {
23
+ const { formatLog: formatLog2, enableColors = true } = options;
24
+ const coloredLevel = getColor(level, enableColors);
25
+ if (formatLog2) {
26
+ return [formatLog2(coloredLevel, timestamp, args)];
27
+ }
28
+ return [`${coloredLevel} ${timestamp}`, ...args];
29
+ }
30
+
31
+ // src/logger.ts
32
+ var defaultFormatTimestamp = (types, date = /* @__PURE__ */ new Date()) => [types.ISO, date.toISOString()];
33
+ var LOG_LEVEL_PRIORITIES = {
34
+ debug: 0,
35
+ info: 1,
36
+ warn: 2,
37
+ error: 3
38
+ };
3
39
  var Logger = class {
40
+ constructor(options = {}) {
41
+ this.options = {
42
+ enableColors: options.enableColors ?? true,
43
+ formatTimestamp: options.formatTimestamp ?? defaultFormatTimestamp,
44
+ formatLog: options.formatLog
45
+ };
46
+ this.level = options.level ?? "debug";
47
+ }
48
+ /**
49
+ * Sets the minimum log level for filtering messages.
50
+ * @param level - The log level to set.
51
+ */
52
+ setLevel(level) {
53
+ this.level = level;
54
+ }
55
+ /**
56
+ * Checks if a log level should be output based on the current log level.
57
+ * @param level - The log level to check.
58
+ * @returns True if the message should be logged.
59
+ */
60
+ shouldLog(level) {
61
+ return LOG_LEVEL_PRIORITIES[level] >= LOG_LEVEL_PRIORITIES[this.level];
62
+ }
4
63
  /**
5
64
  * Logs an info message.
6
- * @param message - The message to log.
65
+ * @param args - The arguments to log.
7
66
  */
8
- info(message) {
9
- console.log(`${chalk.blue("[INFO]")} ${this.getTimestamp()} ${message}`);
67
+ info(...args) {
68
+ if (!this.shouldLog("info")) return;
69
+ const timestamp = formatTimestamp(
70
+ this.options.formatTimestamp,
71
+ TIMESTAMP_TYPES
72
+ );
73
+ console.log(...formatLog("[INFO]", timestamp, args, this.options));
10
74
  }
11
75
  /**
12
76
  * Logs a warning message.
13
- * @param message - The message to log.
77
+ * @param args - The arguments to log.
14
78
  */
15
- warn(message) {
16
- console.log(`${chalk.yellow("[WARN]")} ${this.getTimestamp()} ${message}`);
79
+ warn(...args) {
80
+ if (!this.shouldLog("warn")) return;
81
+ const timestamp = formatTimestamp(
82
+ this.options.formatTimestamp,
83
+ TIMESTAMP_TYPES
84
+ );
85
+ console.log(...formatLog("[WARN]", timestamp, args, this.options));
17
86
  }
18
87
  /**
19
88
  * Logs an error message.
20
- * @param message - The message to log.
89
+ * @param args - The arguments to log.
21
90
  */
22
- error(message) {
23
- console.log(`${chalk.red("[ERROR]")} ${this.getTimestamp()} ${message}`);
91
+ error(...args) {
92
+ if (!this.shouldLog("error")) return;
93
+ const timestamp = formatTimestamp(
94
+ this.options.formatTimestamp,
95
+ TIMESTAMP_TYPES
96
+ );
97
+ console.log(...formatLog("[ERROR]", timestamp, args, this.options));
24
98
  }
25
99
  /**
26
100
  * Logs a debug message.
27
- * @param message - The message to log.
101
+ * @param args - The arguments to log.
28
102
  */
29
- debug(message) {
30
- console.log(`${chalk.gray("[DEBUG]")} ${this.getTimestamp()} ${message}`);
31
- }
32
- getTimestamp() {
33
- return (/* @__PURE__ */ new Date()).toISOString();
34
- }
35
- removeFunction() {
36
- return "Please remove this function";
103
+ debug(...args) {
104
+ if (!this.shouldLog("debug")) return;
105
+ const timestamp = formatTimestamp(
106
+ this.options.formatTimestamp,
107
+ TIMESTAMP_TYPES
108
+ );
109
+ console.log(...formatLog("[DEBUG]", timestamp, args, this.options));
37
110
  }
38
111
  };
39
112
  export {
40
- Logger
113
+ Logger,
114
+ TIMESTAMP_TYPES
41
115
  };
42
116
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import chalk from 'chalk';\n\n/**\n * A simple logger with colored outputs and timestamps.\n */\nexport class Logger {\n /**\n * Logs an info message.\n * @param message - The message to log.\n */\n info(message: string): void {\n console.log(`${chalk.blue('[INFO]')} ${this.getTimestamp()} ${message}`);\n }\n\n /**\n * Logs a warning message.\n * @param message - The message to log.\n */\n warn(message: string): void {\n console.log(`${chalk.yellow('[WARN]')} ${this.getTimestamp()} ${message}`);\n }\n\n /**\n * Logs an error message.\n * @param message - The message to log.\n */\n error(message: string): void {\n console.log(`${chalk.red('[ERROR]')} ${this.getTimestamp()} ${message}`);\n }\n\n /**\n * Logs a debug message.\n * @param message - The message to log.\n */\n debug(message: string): void {\n console.log(`${chalk.gray('[DEBUG]')} ${this.getTimestamp()} ${message}`);\n }\n\n private getTimestamp(): string {\n return new Date().toISOString();\n }\n\n private removeFunction() {\n return 'Please remove this function';\n }\n}\n"],"mappings":";AAAA,OAAO,WAAW;AAKX,IAAM,SAAN,MAAa;AAAA;AAAA;AAAA;AAAA;AAAA,EAKlB,KAAK,SAAuB;AAC1B,YAAQ,IAAI,GAAG,MAAM,KAAK,QAAQ,CAAC,IAAI,KAAK,aAAa,CAAC,IAAI,OAAO,EAAE;AAAA,EACzE;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,KAAK,SAAuB;AAC1B,YAAQ,IAAI,GAAG,MAAM,OAAO,QAAQ,CAAC,IAAI,KAAK,aAAa,CAAC,IAAI,OAAO,EAAE;AAAA,EAC3E;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,SAAuB;AAC3B,YAAQ,IAAI,GAAG,MAAM,IAAI,SAAS,CAAC,IAAI,KAAK,aAAa,CAAC,IAAI,OAAO,EAAE;AAAA,EACzE;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,SAAuB;AAC3B,YAAQ,IAAI,GAAG,MAAM,KAAK,SAAS,CAAC,IAAI,KAAK,aAAa,CAAC,IAAI,OAAO,EAAE;AAAA,EAC1E;AAAA,EAEQ,eAAuB;AAC7B,YAAO,oBAAI,KAAK,GAAE,YAAY;AAAA,EAChC;AAAA,EAEQ,iBAAiB;AACvB,WAAO;AAAA,EACT;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 );\n console.log(...formatLog('[DEBUG]', timestamp, args, this.options));\n }\n}\n"],"mappings":";AAAA,OAAO,WAAW;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;AACT;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,WAAAA,YAAW,eAAe,KAAK,IAAI;AAC3C,QAAM,eAAe,SAAS,OAAO,YAAY;AACjD,MAAIA,YAAW;AACb,WAAO,CAACA,WAAU,cAAc,WAAW,IAAI,CAAC;AAAA,EAClD;AACA,SAAO,CAAC,GAAG,YAAY,IAAI,SAAS,IAAI,GAAG,IAAI;AACjD;;;ACpCA,IAAM,yBAAyB,CAC7B,OACA,OAAa,oBAAI,KAAK,MACM,CAAC,MAAM,KAAK,KAAK,YAAY,CAAC;AAE5D,IAAM,uBAAiD;AAAA,EACrD,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AACT;AAKO,IAAM,SAAN,MAAa;AAAA,EAIlB,YAAY,UAAyB,CAAC,GAAG;AACvC,SAAK,UAAU;AAAA,MACb,cAAc,QAAQ,gBAAgB;AAAA,MACtC,iBAAiB,QAAQ,mBAAmB;AAAA,MAC5C,WAAW,QAAQ;AAAA,IACrB;AACA,SAAK,QAAQ,QAAQ,SAAS;AAAA,EAChC;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,SAAS,OAAuB;AAC9B,SAAK,QAAQ;AAAA,EACf;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOQ,UAAU,OAA0B;AAC1C,WAAO,qBAAqB,KAAK,KAAK,qBAAqB,KAAK,KAAK;AAAA,EACvE;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,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":["formatLog"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@feizk/logger",
3
- "version": "1.0.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,46 +1,8 @@
1
- import chalk from 'chalk';
2
-
3
- /**
4
- * A simple logger with colored outputs and timestamps.
5
- */
6
- export class Logger {
7
- /**
8
- * Logs an info message.
9
- * @param message - The message to log.
10
- */
11
- info(message: string): void {
12
- console.log(`${chalk.blue('[INFO]')} ${this.getTimestamp()} ${message}`);
13
- }
14
-
15
- /**
16
- * Logs a warning message.
17
- * @param message - The message to log.
18
- */
19
- warn(message: string): void {
20
- console.log(`${chalk.yellow('[WARN]')} ${this.getTimestamp()} ${message}`);
21
- }
22
-
23
- /**
24
- * Logs an error message.
25
- * @param message - The message to log.
26
- */
27
- error(message: string): void {
28
- console.log(`${chalk.red('[ERROR]')} ${this.getTimestamp()} ${message}`);
29
- }
30
-
31
- /**
32
- * Logs a debug message.
33
- * @param message - The message to log.
34
- */
35
- debug(message: string): void {
36
- console.log(`${chalk.gray('[DEBUG]')} ${this.getTimestamp()} ${message}`);
37
- }
38
-
39
- private getTimestamp(): string {
40
- return new Date().toISOString();
41
- }
42
-
43
- private removeFunction() {
44
- return 'Please remove this function';
45
- }
46
- }
1
+ export { Logger } from './logger';
2
+ export { TIMESTAMP_TYPES } from './utils';
3
+ export type {
4
+ LoggerOptions,
5
+ LogLevel,
6
+ TimestampTypes,
7
+ TimestampType,
8
+ } from './types';
package/src/logger.ts ADDED
@@ -0,0 +1,102 @@
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()];
10
+
11
+ const LOG_LEVEL_PRIORITIES: Record<LogLevel, number> = {
12
+ debug: 0,
13
+ info: 1,
14
+ warn: 2,
15
+ error: 3,
16
+ };
17
+
18
+ /**
19
+ * A simple logger with colored outputs and timestamps.
20
+ */
21
+ export class Logger {
22
+ private options: LoggerOptions;
23
+ private level: LogLevel;
24
+
25
+ constructor(options: LoggerOptions = {}) {
26
+ this.options = {
27
+ enableColors: options.enableColors ?? true,
28
+ formatTimestamp: options.formatTimestamp ?? defaultFormatTimestamp,
29
+ formatLog: options.formatLog,
30
+ };
31
+ this.level = options.level ?? 'debug';
32
+ }
33
+
34
+ /**
35
+ * Sets the minimum log level for filtering messages.
36
+ * @param level - The log level to set.
37
+ */
38
+ setLevel(level: LogLevel): void {
39
+ this.level = level;
40
+ }
41
+
42
+ /**
43
+ * Checks if a log level should be output based on the current log level.
44
+ * @param level - The log level to check.
45
+ * @returns True if the message should be logged.
46
+ */
47
+ private shouldLog(level: LogLevel): boolean {
48
+ return LOG_LEVEL_PRIORITIES[level] >= LOG_LEVEL_PRIORITIES[this.level];
49
+ }
50
+
51
+ /**
52
+ * Logs an info message.
53
+ * @param args - The arguments to log.
54
+ */
55
+ info(...args: unknown[]): void {
56
+ if (!this.shouldLog('info')) return;
57
+ const timestamp = formatTimestamp(
58
+ this.options.formatTimestamp!,
59
+ TIMESTAMP_TYPES,
60
+ );
61
+ console.log(...formatLog('[INFO]', timestamp, args, this.options));
62
+ }
63
+
64
+ /**
65
+ * Logs a warning message.
66
+ * @param args - The arguments to log.
67
+ */
68
+ warn(...args: unknown[]): void {
69
+ if (!this.shouldLog('warn')) return;
70
+ const timestamp = formatTimestamp(
71
+ this.options.formatTimestamp!,
72
+ TIMESTAMP_TYPES,
73
+ );
74
+ console.log(...formatLog('[WARN]', timestamp, args, this.options));
75
+ }
76
+
77
+ /**
78
+ * Logs an error message.
79
+ * @param args - The arguments to log.
80
+ */
81
+ error(...args: unknown[]): void {
82
+ if (!this.shouldLog('error')) return;
83
+ const timestamp = formatTimestamp(
84
+ this.options.formatTimestamp!,
85
+ TIMESTAMP_TYPES,
86
+ );
87
+ console.log(...formatLog('[ERROR]', timestamp, args, this.options));
88
+ }
89
+
90
+ /**
91
+ * Logs a debug message.
92
+ * @param args - The arguments to log.
93
+ */
94
+ debug(...args: unknown[]): void {
95
+ if (!this.shouldLog('debug')) return;
96
+ const timestamp = formatTimestamp(
97
+ this.options.formatTimestamp!,
98
+ TIMESTAMP_TYPES,
99
+ );
100
+ console.log(...formatLog('[DEBUG]', timestamp, args, this.options));
101
+ }
102
+ }
package/src/types.ts ADDED
@@ -0,0 +1,19 @@
1
+ export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
2
+
3
+ export type TimestampType = 'iso' | 'locale' | 'custom';
4
+
5
+ export interface TimestampTypes {
6
+ ISO: 'iso';
7
+ Locale: 'locale';
8
+ Custom: 'custom';
9
+ }
10
+
11
+ export interface LoggerOptions {
12
+ enableColors?: boolean;
13
+ formatTimestamp?: (
14
+ types: TimestampTypes,
15
+ date?: Date,
16
+ ) => [TimestampType, string];
17
+ formatLog?: (level: string, timestamp: string, args: unknown[]) => string;
18
+ level?: LogLevel;
19
+ }
package/src/utils.ts ADDED
@@ -0,0 +1,42 @@
1
+ import chalk from 'chalk';
2
+ import type { LoggerOptions, TimestampTypes } from './types';
3
+
4
+ export const TIMESTAMP_TYPES: TimestampTypes = {
5
+ ISO: 'iso',
6
+ Locale: 'locale',
7
+ Custom: 'custom',
8
+ };
9
+
10
+ export function formatTimestamp(
11
+ formatTimestampFn: NonNullable<LoggerOptions['formatTimestamp']>,
12
+ types: TimestampTypes,
13
+ date: Date = new Date(),
14
+ ): string {
15
+ const [, timestamp] = formatTimestampFn(types, date);
16
+ return timestamp;
17
+ }
18
+
19
+ export function getColor(level: string, enableColors: boolean): string {
20
+ if (!enableColors) return level;
21
+ const colors: Record<string, string> = {
22
+ '[INFO]': chalk.blue(level),
23
+ '[WARN]': chalk.yellow(level),
24
+ '[ERROR]': chalk.red(level),
25
+ '[DEBUG]': chalk.gray(level),
26
+ };
27
+ return colors[level] || level;
28
+ }
29
+
30
+ export function formatLog(
31
+ level: string,
32
+ timestamp: string,
33
+ args: unknown[],
34
+ options: LoggerOptions,
35
+ ): [string, ...unknown[]] {
36
+ const { formatLog, enableColors = true } = options;
37
+ const coloredLevel = getColor(level, enableColors);
38
+ if (formatLog) {
39
+ return [formatLog(coloredLevel, timestamp, args)];
40
+ }
41
+ return [`${coloredLevel} ${timestamp}`, ...args];
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;
@@ -27,33 +27,33 @@ describe('Logger', () => {
27
27
 
28
28
  it('should have info method', () => {
29
29
  logger.info('test message');
30
- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('[INFO]'));
31
30
  expect(consoleSpy).toHaveBeenCalledWith(
32
- expect.stringContaining('test message'),
31
+ expect.stringContaining('[INFO]'),
32
+ 'test message',
33
33
  );
34
34
  });
35
35
 
36
36
  it('should have warn method', () => {
37
37
  logger.warn('test message');
38
- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('[WARN]'));
39
38
  expect(consoleSpy).toHaveBeenCalledWith(
40
- expect.stringContaining('test message'),
39
+ expect.stringContaining('[WARN]'),
40
+ 'test message',
41
41
  );
42
42
  });
43
43
 
44
44
  it('should have error method', () => {
45
45
  logger.error('test message');
46
- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('[ERROR]'));
47
46
  expect(consoleSpy).toHaveBeenCalledWith(
48
- expect.stringContaining('test message'),
47
+ expect.stringContaining('[ERROR]'),
48
+ 'test message',
49
49
  );
50
50
  });
51
51
 
52
52
  it('should have debug method', () => {
53
53
  logger.debug('test message');
54
- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('[DEBUG]'));
55
54
  expect(consoleSpy).toHaveBeenCalledWith(
56
- expect.stringContaining('test message'),
55
+ expect.stringContaining('[DEBUG]'),
56
+ 'test message',
57
57
  );
58
58
  });
59
59
 
@@ -62,4 +62,121 @@ describe('Logger', () => {
62
62
  const callArgs = consoleSpy.mock.calls[0][0];
63
63
  expect(callArgs).toMatch(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z/);
64
64
  });
65
+
66
+ it('should handle multiple arguments', () => {
67
+ logger.info('hello', 'world', 42, { key: 'value' });
68
+ const calls = consoleSpy.mock.calls[0];
69
+ expect(calls[0]).toMatch(/\[INFO\]/);
70
+ expect(calls[1]).toBe('hello');
71
+ expect(calls[2]).toBe('world');
72
+ expect(calls[3]).toBe(42);
73
+ expect(calls[4]).toEqual({ key: 'value' });
74
+ });
75
+
76
+ it('should disable colors when enableColors is false', () => {
77
+ const noColorLogger = new Logger({ enableColors: false });
78
+ noColorLogger.info('test message');
79
+ const callArgs = consoleSpy.mock.calls[0][0];
80
+ expect(callArgs).toContain('[INFO]'); // Should not have ANSI codes
81
+ expect(callArgs).not.toContain('\u001b['); // ANSI escape code
82
+ });
83
+
84
+ it('should use locale timestamp format', () => {
85
+ const localeLogger = new Logger({
86
+ formatTimestamp: (types) => [types.Locale, new Date().toLocaleString()],
87
+ });
88
+ localeLogger.info('test');
89
+ const callArgs = consoleSpy.mock.calls[0][0];
90
+ expect(callArgs).toMatch(/\d{1,2}\/\d{1,2}\/\d{4}/); // Basic locale date check
91
+ });
92
+
93
+ it('should use custom timestamp function', () => {
94
+ const customLogger = new Logger({
95
+ formatTimestamp: () => [TIMESTAMP_TYPES.Custom, 'custom-time'],
96
+ });
97
+ customLogger.info('test');
98
+ const callArgs = consoleSpy.mock.calls[0][0];
99
+ expect(callArgs).toContain('custom-time');
100
+ });
101
+
102
+ it('should use custom log format', () => {
103
+ const customLogger = new Logger({
104
+ formatLog: (level, timestamp, args) =>
105
+ `${timestamp} ${level}: ${args.join(' ')}`,
106
+ });
107
+ customLogger.warn('hello', 'world');
108
+ const callArgs = consoleSpy.mock.calls[0][0];
109
+ expect(callArgs).toMatch(
110
+ /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z \[WARN\]: hello world/,
111
+ );
112
+ });
113
+
114
+ it('should default to debug log level', () => {
115
+ const defaultLogger = new Logger();
116
+ defaultLogger.debug('debug message');
117
+ expect(consoleSpy).toHaveBeenCalledWith(
118
+ expect.stringContaining('[DEBUG]'),
119
+ 'debug message',
120
+ );
121
+ });
122
+
123
+ it('should filter logs below the set level', () => {
124
+ const infoLogger = new Logger({ level: 'info' });
125
+ infoLogger.debug('debug message');
126
+ expect(consoleSpy).not.toHaveBeenCalled();
127
+
128
+ infoLogger.info('info message');
129
+ expect(consoleSpy).toHaveBeenCalledWith(
130
+ expect.stringContaining('[INFO]'),
131
+ 'info message',
132
+ );
133
+ });
134
+
135
+ it('should allow all levels when set to debug', () => {
136
+ const debugLogger = new Logger({ level: 'debug' });
137
+ debugLogger.debug('debug');
138
+ debugLogger.info('info');
139
+ debugLogger.warn('warn');
140
+ debugLogger.error('error');
141
+ expect(consoleSpy).toHaveBeenCalledTimes(4);
142
+ });
143
+
144
+ it('should filter debug and info when set to warn', () => {
145
+ const warnLogger = new Logger({ level: 'warn' });
146
+ warnLogger.debug('debug');
147
+ warnLogger.info('info');
148
+ expect(consoleSpy).not.toHaveBeenCalled();
149
+
150
+ warnLogger.warn('warn');
151
+ warnLogger.error('error');
152
+ expect(consoleSpy).toHaveBeenCalledTimes(2);
153
+ });
154
+
155
+ it('should only log errors when set to error', () => {
156
+ const errorLogger = new Logger({ level: 'error' });
157
+ errorLogger.debug('debug');
158
+ errorLogger.info('info');
159
+ errorLogger.warn('warn');
160
+ expect(consoleSpy).not.toHaveBeenCalled();
161
+
162
+ errorLogger.error('error');
163
+ expect(consoleSpy).toHaveBeenCalledWith(
164
+ expect.stringContaining('[ERROR]'),
165
+ 'error',
166
+ );
167
+ });
168
+
169
+ it('should allow changing log level dynamically', () => {
170
+ const logger = new Logger();
171
+ logger.setLevel('error');
172
+ logger.debug('debug');
173
+ expect(consoleSpy).not.toHaveBeenCalled();
174
+
175
+ logger.setLevel('debug');
176
+ logger.debug('debug');
177
+ expect(consoleSpy).toHaveBeenCalledWith(
178
+ expect.stringContaining('[DEBUG]'),
179
+ 'debug',
180
+ );
181
+ });
65
182
  });