@feizk/logger 1.5.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@feizk/logger",
3
- "version": "1.5.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,45 +0,0 @@
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/src/index.ts DELETED
@@ -1,8 +0,0 @@
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 DELETED
@@ -1,102 +0,0 @@
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 DELETED
@@ -1,19 +0,0 @@
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 DELETED
@@ -1,42 +0,0 @@
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
- }
@@ -1,182 +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, TIMESTAMP_TYPES } 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({
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
- });
182
- });
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
- });