@feizk/logger 1.4.0 → 1.5.1

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/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, args, this.options));\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,mBAAkB;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,aAAAA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AAA,EAMA,QAAQ,MAAuB;AAC7B,QAAI,CAAC,KAAK,UAAU,MAAM,EAAG;AAC7B,UAAM,YAAY,gBAAgB,KAAK,OAAO;AAC9C,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,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":["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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;AACT;AAEO,SAAS,SAAS,OAAe,cAA+B;AACrE,MAAI,CAAC,aAAc,QAAO;AAC1B,QAAM,SAAiC;AAAA,IACrC,UAAU,aAAAA,QAAM,KAAK,KAAK;AAAA,IAC1B,UAAU,aAAAA,QAAM,OAAO,KAAK;AAAA,IAC5B,WAAW,aAAAA,QAAM,IAAI,KAAK;AAAA,IAC1B,WAAW,aAAAA,QAAM,KAAK,KAAK;AAAA,EAC7B;AACA,SAAO,OAAO,KAAK,KAAK;AAC1B;AAEO,SAAS,UACd,OACA,WACA,MACA,SACwB;AACxB,QAAM,EAAE,WAAAC,YAAW,eAAe,KAAK,IAAI;AAC3C,QAAM,eAAe,SAAS,OAAO,YAAY;AACjD,MAAIA,YAAW;AACb,WAAO,CAACA,WAAU,cAAc,WAAW,IAAI,CAAC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C9B,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,eAAe,KAAK,IAAI;AAC3C,QAAM,eAAe,SAAS,OAAO,YAAY;AACjD,MAAI,WAAW;AACb,WAAO,CAAC,UAAU,cAAc,WAAW,IAAI,CAAC;AAAA,EAClD;AACA,SAAO,CAAC,GAAG,YAAY,IAAI,SAAS,IAAI,GAAG,IAAI;AACjD;;;ACxCA,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,WAAW,QAAQ,YAAY;AAAA,EACtC;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,YAAY,OAAuB;AACjC,SAAK,WAAW;AAAA,EAClB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOQ,UAAU,OAA0B;AAC1C,WAAO,qBAAqB,KAAK,KAAK,qBAAqB,KAAK,QAAQ;AAAA,EAC1E;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,QAAQ,MAAuB;AAC7B,QAAI,CAAC,KAAK,UAAU,MAAM,EAAG;AAC7B,UAAM,YAAY,gBAAgB,KAAK,OAAO;AAC9C,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,gBAAgB,KAAK,OAAO;AAC9C,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,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 );\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,KAA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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.4.0",
3
+ "version": "1.5.1",
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",
@@ -14,6 +14,10 @@
14
14
  "@types/node": "^20.0.0",
15
15
  "vitest": "^1.6.1"
16
16
  },
17
+ "files": [
18
+ "dist",
19
+ "README.md"
20
+ ],
17
21
  "keywords": [
18
22
  "logger",
19
23
  "console",
package/CHANGELOG.md DELETED
@@ -1,30 +0,0 @@
1
- # @feizk/logger
2
-
3
- ## 1.4.0
4
-
5
- ### Minor Changes
6
-
7
- - 2b7b1eb: - Added `LogLevel` type ('debug' | 'info' | 'warn' | 'error') and `logLevel` option to `LoggerOptions` in `types.ts`
8
- - Updated `logger.ts` to implement log level filtering with a `LOG_LEVEL_PRIORITIES` constant, `shouldLog` private method, and checks before each log call
9
- - Added `setLogLevel` method to `logger.ts` for dynamic runtime level changes
10
- - Exported `LogLevel` type from `index.ts` for external use
11
- - Added comprehensive test cases in `logger.test.ts` for filtering behavior at different levels, dynamic level changes, and default behavior
12
- - Updated `README.md` with `logLevel` option documentation, usage examples, and API details for the new method
13
-
14
- ## 1.3.0
15
-
16
- ### Minor Changes
17
-
18
- - 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
19
-
20
- ## 1.2.0
21
-
22
- ### Minor Changes
23
-
24
- - 4b70f01: Accept multiple arguments and Any type of arguments on all Logger methods
25
-
26
- ## 1.1.0
27
-
28
- ### Minor Changes
29
-
30
- - ebc4e0b: Add success logging method to Logger class
package/src/index.ts DELETED
@@ -1,2 +0,0 @@
1
- export { Logger } from './logger';
2
- export type { LoggerOptions, LogLevel } from './types';
package/src/logger.ts DELETED
@@ -1,83 +0,0 @@
1
- import type { LoggerOptions, LogLevel } from './types';
2
- import { formatTimestamp, formatLog } from './utils';
3
-
4
- const LOG_LEVEL_PRIORITIES: Record<LogLevel, number> = {
5
- debug: 0,
6
- info: 1,
7
- warn: 2,
8
- error: 3,
9
- };
10
-
11
- /**
12
- * A simple logger with colored outputs and timestamps.
13
- */
14
- export class Logger {
15
- private options: LoggerOptions;
16
- private logLevel: LogLevel;
17
-
18
- constructor(options: LoggerOptions = {}) {
19
- this.options = {
20
- enableColors: options.enableColors ?? true,
21
- timestampFormat: options.timestampFormat ?? 'iso',
22
- logFormat: options.logFormat,
23
- };
24
- this.logLevel = options.logLevel ?? 'debug';
25
- }
26
-
27
- /**
28
- * Sets the minimum log level for filtering messages.
29
- * @param level - The log level to set.
30
- */
31
- setLogLevel(level: LogLevel): void {
32
- this.logLevel = level;
33
- }
34
-
35
- /**
36
- * Checks if a log level should be output based on the current log level.
37
- * @param level - The log level to check.
38
- * @returns True if the message should be logged.
39
- */
40
- private shouldLog(level: LogLevel): boolean {
41
- return LOG_LEVEL_PRIORITIES[level] >= LOG_LEVEL_PRIORITIES[this.logLevel];
42
- }
43
-
44
- /**
45
- * Logs an info message.
46
- * @param args - The arguments to log.
47
- */
48
- info(...args: unknown[]): void {
49
- if (!this.shouldLog('info')) return;
50
- const timestamp = formatTimestamp(this.options);
51
- console.log(...formatLog('[INFO]', timestamp, args, this.options));
52
- }
53
-
54
- /**
55
- * Logs a warning message.
56
- * @param args - The arguments to log.
57
- */
58
- warn(...args: unknown[]): void {
59
- if (!this.shouldLog('warn')) return;
60
- const timestamp = formatTimestamp(this.options);
61
- console.log(...formatLog('[WARN]', timestamp, args, this.options));
62
- }
63
-
64
- /**
65
- * Logs an error message.
66
- * @param args - The arguments to log.
67
- */
68
- error(...args: unknown[]): void {
69
- if (!this.shouldLog('error')) return;
70
- const timestamp = formatTimestamp(this.options);
71
- console.log(...formatLog('[ERROR]', timestamp, args, this.options));
72
- }
73
-
74
- /**
75
- * Logs a debug message.
76
- * @param args - The arguments to log.
77
- */
78
- debug(...args: unknown[]): void {
79
- if (!this.shouldLog('debug')) return;
80
- const timestamp = formatTimestamp(this.options);
81
- console.log(...formatLog('[DEBUG]', timestamp, args, this.options));
82
- }
83
- }
package/src/types.ts DELETED
@@ -1,8 +0,0 @@
1
- export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
2
-
3
- export interface LoggerOptions {
4
- enableColors?: boolean;
5
- timestampFormat?: 'iso' | 'locale' | ((date: Date) => string);
6
- logFormat?: (level: string, timestamp: string, args: unknown[]) => string;
7
- logLevel?: LogLevel;
8
- }
package/src/utils.ts DELETED
@@ -1,44 +0,0 @@
1
- import chalk from 'chalk';
2
- import type { LoggerOptions } from './types';
3
-
4
- export function formatTimestamp(
5
- options: LoggerOptions,
6
- date: Date = new Date(),
7
- ): 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
- }
19
- }
20
-
21
- export function getColor(level: string, enableColors: boolean): string {
22
- if (!enableColors) return level;
23
- const colors: Record<string, string> = {
24
- '[INFO]': chalk.blue(level),
25
- '[WARN]': chalk.yellow(level),
26
- '[ERROR]': chalk.red(level),
27
- '[DEBUG]': chalk.gray(level),
28
- };
29
- return colors[level] || level;
30
- }
31
-
32
- export function formatLog(
33
- level: string,
34
- timestamp: string,
35
- args: unknown[],
36
- options: LoggerOptions,
37
- ): [string, ...unknown[]] {
38
- const { logFormat, enableColors = true } = options;
39
- const coloredLevel = getColor(level, enableColors);
40
- if (logFormat) {
41
- return [logFormat(coloredLevel, timestamp, args)];
42
- }
43
- return [`${coloredLevel} ${timestamp}`, ...args];
44
- }
@@ -1,180 +0,0 @@
1
- import {
2
- describe,
3
- it,
4
- expect,
5
- vi,
6
- beforeEach,
7
- afterEach,
8
- type MockInstance,
9
- } from 'vitest';
10
- import { Logger } from '../src/index';
11
-
12
- describe('Logger', () => {
13
- let logger: Logger;
14
- let consoleSpy: MockInstance<
15
- [message?: unknown, ...optionalParams: unknown[]],
16
- void
17
- >;
18
-
19
- beforeEach(() => {
20
- logger = new Logger();
21
- consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
22
- });
23
-
24
- afterEach(() => {
25
- consoleSpy.mockRestore();
26
- });
27
-
28
- it('should have info method', () => {
29
- logger.info('test message');
30
- expect(consoleSpy).toHaveBeenCalledWith(
31
- expect.stringContaining('[INFO]'),
32
- 'test message',
33
- );
34
- });
35
-
36
- it('should have warn method', () => {
37
- logger.warn('test message');
38
- expect(consoleSpy).toHaveBeenCalledWith(
39
- expect.stringContaining('[WARN]'),
40
- 'test message',
41
- );
42
- });
43
-
44
- it('should have error method', () => {
45
- logger.error('test message');
46
- expect(consoleSpy).toHaveBeenCalledWith(
47
- expect.stringContaining('[ERROR]'),
48
- 'test message',
49
- );
50
- });
51
-
52
- it('should have debug method', () => {
53
- logger.debug('test message');
54
- expect(consoleSpy).toHaveBeenCalledWith(
55
- expect.stringContaining('[DEBUG]'),
56
- 'test message',
57
- );
58
- });
59
-
60
- it('should include timestamp in logs', () => {
61
- logger.info('test');
62
- const callArgs = consoleSpy.mock.calls[0][0];
63
- expect(callArgs).toMatch(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z/);
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({ timestampFormat: 'locale' });
86
- localeLogger.info('test');
87
- const callArgs = consoleSpy.mock.calls[0][0];
88
- expect(callArgs).toMatch(/\d{1,2}\/\d{1,2}\/\d{4}/); // Basic locale date check
89
- });
90
-
91
- it('should use custom timestamp function', () => {
92
- const customLogger = new Logger({
93
- timestampFormat: () => 'custom-time',
94
- });
95
- customLogger.info('test');
96
- const callArgs = consoleSpy.mock.calls[0][0];
97
- expect(callArgs).toContain('custom-time');
98
- });
99
-
100
- it('should use custom log format', () => {
101
- const customLogger = new Logger({
102
- logFormat: (level, timestamp, args) =>
103
- `${timestamp} ${level}: ${args.join(' ')}`,
104
- });
105
- customLogger.warn('hello', 'world');
106
- const callArgs = consoleSpy.mock.calls[0][0];
107
- expect(callArgs).toMatch(
108
- /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z \[WARN\]: hello world/,
109
- );
110
- });
111
-
112
- it('should default to debug log level', () => {
113
- const defaultLogger = new Logger();
114
- defaultLogger.debug('debug message');
115
- expect(consoleSpy).toHaveBeenCalledWith(
116
- expect.stringContaining('[DEBUG]'),
117
- 'debug message',
118
- );
119
- });
120
-
121
- it('should filter logs below the set level', () => {
122
- const infoLogger = new Logger({ logLevel: 'info' });
123
- infoLogger.debug('debug message');
124
- expect(consoleSpy).not.toHaveBeenCalled();
125
-
126
- infoLogger.info('info message');
127
- expect(consoleSpy).toHaveBeenCalledWith(
128
- expect.stringContaining('[INFO]'),
129
- 'info message',
130
- );
131
- });
132
-
133
- it('should allow all levels when set to debug', () => {
134
- const debugLogger = new Logger({ logLevel: 'debug' });
135
- debugLogger.debug('debug');
136
- debugLogger.info('info');
137
- debugLogger.warn('warn');
138
- debugLogger.error('error');
139
- expect(consoleSpy).toHaveBeenCalledTimes(4);
140
- });
141
-
142
- it('should filter debug and info when set to warn', () => {
143
- const warnLogger = new Logger({ logLevel: 'warn' });
144
- warnLogger.debug('debug');
145
- warnLogger.info('info');
146
- expect(consoleSpy).not.toHaveBeenCalled();
147
-
148
- warnLogger.warn('warn');
149
- warnLogger.error('error');
150
- expect(consoleSpy).toHaveBeenCalledTimes(2);
151
- });
152
-
153
- it('should only log errors when set to error', () => {
154
- const errorLogger = new Logger({ logLevel: 'error' });
155
- errorLogger.debug('debug');
156
- errorLogger.info('info');
157
- errorLogger.warn('warn');
158
- expect(consoleSpy).not.toHaveBeenCalled();
159
-
160
- errorLogger.error('error');
161
- expect(consoleSpy).toHaveBeenCalledWith(
162
- expect.stringContaining('[ERROR]'),
163
- 'error',
164
- );
165
- });
166
-
167
- it('should allow changing log level dynamically', () => {
168
- const logger = new Logger();
169
- logger.setLogLevel('error');
170
- logger.debug('debug');
171
- expect(consoleSpy).not.toHaveBeenCalled();
172
-
173
- logger.setLogLevel('debug');
174
- logger.debug('debug');
175
- expect(consoleSpy).toHaveBeenCalledWith(
176
- expect.stringContaining('[DEBUG]'),
177
- 'debug',
178
- );
179
- });
180
- });
package/tsup.config.ts DELETED
@@ -1,10 +0,0 @@
1
- import { defineConfig } from 'tsup';
2
-
3
- export default defineConfig({
4
- entry: ['src/index.ts'],
5
- format: ['cjs', 'esm'],
6
- dts: true,
7
- splitting: false,
8
- sourcemap: true,
9
- clean: true,
10
- });