@skax/logger 1.0.1 → 2.0.0-beta.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/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  The MIT License (MIT)
2
2
 
3
- Copyright (c) 2023 Shine Shao
3
+ Copyright (c) 2026 Shine Shao
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,48 +1,168 @@
1
- ## @skax/logger
1
+ # @skax/logger
2
2
 
3
- ![build](https://github.com/freeshineit/skax-logger/workflows/build/badge.svg) ![Download](https://img.shields.io/npm/dm/@skax/logger.svg) ![Version](https://img.shields.io/npm/v/@skax/logger.svg) ![License](https://img.shields.io/npm/l/@skax/logger.svg)
3
+ A lightweight, zero-dependency logger with **level filtering**, **module prefix**, and **caller-context output**.
4
4
 
5
- ### Usage
5
+ Uses `Proxy` + `Reflect` so DevTools source links point to the actual call site — not logger internals.
6
6
 
7
- ```sh
8
- yarn add @skax/logger
7
+ ## Features
8
+
9
+ - 🎚️ **Level filtering** — `NONE` / `ERROR` / `WARN` / `INFO` / `DEBUG`, switchable at runtime
10
+ - 🏷️ **Module prefix** — each logger carries a `[ModuleName]` tag for easy identification
11
+ - 📍 **Caller-context output** — browser DevTools link to the real call site, not `logger.ts:140`
12
+ - 🪞 **Proxy-based dispatch** — zero-overhead: returns `NOOP` when the level suppresses output
13
+ - 📦 **Tree-shakable** — ESM & CJS builds, no dependencies
14
+ - 🌐 **UMD build** — drop-in `<script>` for browser usage
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ npm install @skax/logger
20
+ ```
21
+
22
+ ## Quick Start
23
+
24
+ ```ts
25
+ import { Logger } from "@skax/logger";
26
+
27
+ const logger = new Logger("MyModule", Logger.LEVEL.DEBUG);
28
+
29
+ logger.info("Server started", { port: 3000 });
30
+ // → [MyModule] [INFO] Server started { port: 3000 }
31
+
32
+ logger.warn("Disk space low", { remaining: "2%" });
33
+ // → [MyModule] [WARN] Disk space low { remaining: "2%" }
34
+
35
+ logger.error("Connection failed", new Error("timeout"));
36
+ // → [MyModule] [ERROR] Connection failed Error: timeout
37
+ ```
38
+
39
+ ## API
40
+
41
+ ### `new Logger(prefix?, level?)`
42
+
43
+ Creates a new logger instance.
44
+
45
+ | Parameter | Type | Default | Description |
46
+ | --------- | -------- | ------------------- | --------------------------------- |
47
+ | `prefix` | `string` | `"Logger"` | Module name shown in `[brackets]` |
48
+ | `level` | `Level` | `Logger.LEVEL.WARN` | Minimum log level to output |
49
+
50
+ <br/>
51
+
52
+ ```ts
53
+ const logger = new Logger("API", Logger.LEVEL.INFO);
54
+ ```
55
+
56
+ ### Log Levels
57
+
58
+ Accessible via `Logger.LEVEL`:
59
+
60
+ | Constant | Value | Description |
61
+ | -------------------- | ----- | ------------------------------ |
62
+ | `Logger.LEVEL.NONE` | `0` | Suppress all output |
63
+ | `Logger.LEVEL.ERROR` | `1` | Only errors |
64
+ | `Logger.LEVEL.WARN` | `2` | Warnings and errors |
65
+ | `Logger.LEVEL.INFO` | `3` | Info, warnings, errors |
66
+ | `Logger.LEVEL.DEBUG` | `4` | All messages (including debug) |
67
+
68
+ ### Methods
69
+
70
+ ```ts
71
+ logger.error(...args); // Always output (unless level = NONE)
72
+ logger.warn(...args); // Output when level ≥ WARN
73
+ logger.info(...args); // Output when level ≥ INFO
74
+ logger.debug(...args); // Output when level ≥ DEBUG
75
+ logger.group(label); // console.group when level ≥ DEBUG
76
+ logger.groupEnd(); // console.groupEnd when level ≥ DEBUG
77
+ ```
78
+
79
+ ### `setLevel(level)` / `getLevel()`
80
+
81
+ Change or read the log level at runtime:
82
+
83
+ ```ts
84
+ logger.setLevel(Logger.LEVEL.DEBUG); // enable all logs
85
+ logger.setLevel(Logger.LEVEL.NONE); // silence everything
86
+
87
+ console.log(logger.getLevel()); // 0
88
+ ```
89
+
90
+ ### `getLogger(debug?)`
91
+
92
+ Returns a global singleton logger with prefix `"Logger"`:
93
+
94
+ ```ts
95
+ import { getLogger } from "@skax/logger";
96
+
97
+ const log = getLogger(true); // DEBUG level
98
+ log.info("App initialized"); // → [Logger] [INFO] App initialized
9
99
  ```
10
100
 
101
+ The singleton is lazily created on first call — subsequent calls return the same instance.
102
+
103
+ ### TypeScript
104
+
11
105
  ```ts
12
- import Logger from '@skax/logger';
106
+ import { Logger } from "@skax/logger";
13
107
 
14
- const logger = new Logger();
108
+ // The level type is inferred from Logger.LEVEL:
109
+ const level: (typeof Logger.LEVEL)[keyof typeof Logger.LEVEL] = Logger.LEVEL.DEBUG;
15
110
 
16
- logger.d('console.debug print'); // debug
17
- logger.v('console.log print'); // log
18
- logger.i('console.info print'); // info
19
- logger.w('console.warn print'); // warn
20
- logger.e('console.error print'); // error
111
+ // Or just let TS infer:
112
+ const logger = new Logger("TSModule", Logger.LEVEL.INFO);
113
+ logger.setLevel(Logger.LEVEL.DEBUG);
114
+ const current = logger.getLevel(); // 0 | 1 | 2 | 3 | 4
21
115
  ```
22
116
 
23
- ### umd
117
+ ## How It Works
118
+
119
+ The constructor returns a **Proxy** that intercepts property access. When you call `logger.info(...)`:
120
+
121
+ 1. The Proxy's `get` trap checks `target._level >= Logger.LEVEL.INFO`
122
+ 2. If `true` → returns `console.info.bind(console, "[prefix] [INFO]")` — called in **your** stack frame
123
+ 3. If `false` → returns `Logger.NOOP` — a no-op function, zero cost
124
+
125
+ ```
126
+ yourFile.ts:42 → logger.info("hello")
127
+
128
+ Proxy.get("info")
129
+
130
+ console.info.bind(console, "[Demo] [INFO]")
131
+
132
+ DevTools source → yourFile.ts:42 ✓
133
+ ```
134
+
135
+ ## Browser Usage (UMD)
24
136
 
25
137
  ```html
26
- <script src="./index.umd.js"></script>
138
+ <script src="./node_modules/@skax/logger/dist/index.umd.js"></script>
27
139
  <script>
28
- (function () {
29
- const logger = new Logger();
140
+ const logger = new Logger("Browser", Logger.LEVEL.DEBUG);
141
+ logger.info("Hello from the browser!");
142
+ </script>
143
+ ```
30
144
 
31
- logger.v(logger.version());
145
+ A live demo is included at [`public/index.html`](public/index.html).
32
146
 
33
- logger.d('1234132');
34
- logger.v('1234132');
35
- logger.i('1234132');
36
- logger.w('1234132');
37
- logger.e('1234132');
147
+ ## Build
38
148
 
39
- logger.setOptions({ level: 'WARN' });
149
+ ```bash
150
+ npm run build # Production build (CJS + ESM + UMD)
151
+ npm run dev # Development watch mode
152
+ npm run test # Run tests with coverage
153
+ ```
154
+
155
+ Output:
40
156
 
41
- logger.d('2-1234132');
42
- logger.v('2-1234132');
43
- logger.i('2-1234132');
44
- logger.w('2-1234132');
45
- logger.e('2-1234132');
46
- })();
47
- </script>
48
157
  ```
158
+ dist/
159
+ ├── index.cjs # CommonJS
160
+ ├── index.esm.js # ES Module
161
+ ├── index.umd.js # UMD (browser)
162
+ └── types/
163
+ └── index.d.ts # TypeScript declarations
164
+ ```
165
+
166
+ ## License
167
+
168
+ MIT
@@ -0,0 +1,166 @@
1
+ # @skax/logger
2
+
3
+ 轻量级、零依赖的日志工具,支持**分级过滤**、**模块前缀**和**调用者上下文输出**。
4
+
5
+ 通过 `Proxy` + `Reflect` 使得浏览器 DevTools 的源文件链接指向真正的调用位置,而非 logger 内部。
6
+
7
+ ## 特性
8
+
9
+ - 🎚️ **分级过滤** — `NONE` / `ERROR` / `WARN` / `INFO` / `DEBUG`,运行时动态切换
10
+ - 🏷️ **模块前缀** — 每个 logger 携带 `[模块名]` 标签,便于识别来源
11
+ - 📍 **调用者上下文** — DevTools 源链接指向实际调用位置,而非 `logger.ts:140`
12
+ - 🪞 **Proxy 分发** — 零开销:级别不满足时返回 `NOOP` 空函数
13
+ - 📦 **Tree-shakable** — ESM & CJS 双构建,零依赖
14
+ - 🌐 **UMD 构建** — 浏览器 `<script>` 直接引入
15
+
16
+ ## 安装
17
+
18
+ ```bash
19
+ npm install @skax/logger
20
+ ```
21
+
22
+ ## 快速开始
23
+
24
+ ```ts
25
+ import { Logger } from "@skax/logger";
26
+
27
+ const logger = new Logger("MyModule", Logger.LEVEL.DEBUG);
28
+
29
+ logger.info("服务启动", { port: 3000 });
30
+ // → [MyModule] [INFO] 服务启动 { port: 3000 }
31
+
32
+ logger.warn("磁盘空间不足", { remaining: "2%" });
33
+ // → [MyModule] [WARN] 磁盘空间不足 { remaining: "2%" }
34
+
35
+ logger.error("连接失败", new Error("超时"));
36
+ // → [MyModule] [ERROR] 连接失败 Error: 超时
37
+ ```
38
+
39
+ ## API
40
+
41
+ ### `new Logger(prefix?, level?)`
42
+
43
+ 创建一个 logger 实例。
44
+
45
+ | 参数 | 类型 | 默认值 | 说明 |
46
+ | -------- | -------- | ------------------- | ------------------------------ |
47
+ | `prefix` | `string` | `"Logger"` | 模块名称,显示在 `[方括号]` 中 |
48
+ | `level` | `Level` | `Logger.LEVEL.WARN` | 最低输出级别 |
49
+
50
+ ```ts
51
+ const logger = new Logger("API", Logger.LEVEL.INFO);
52
+ ```
53
+
54
+ ### 日志等级
55
+
56
+ 通过 `Logger.LEVEL` 访问:
57
+
58
+ | 常量 | 值 | 说明 |
59
+ | -------------------- | --- | ------------------------ |
60
+ | `Logger.LEVEL.NONE` | `0` | 关闭所有日志 |
61
+ | `Logger.LEVEL.ERROR` | `1` | 仅输出 error |
62
+ | `Logger.LEVEL.WARN` | `2` | 输出 warn 及 error |
63
+ | `Logger.LEVEL.INFO` | `3` | 输出 info、warn、error |
64
+ | `Logger.LEVEL.DEBUG` | `4` | 输出所有日志(含 debug) |
65
+
66
+ ### 日志方法
67
+
68
+ ```ts
69
+ logger.error(...args); // 始终输出(除非 level = NONE)
70
+ logger.warn(...args); // level ≥ WARN 时输出
71
+ logger.info(...args); // level ≥ INFO 时输出
72
+ logger.debug(...args); // level ≥ DEBUG 时输出
73
+ logger.group(label); // level ≥ DEBUG 时调用 console.group
74
+ logger.groupEnd(); // level ≥ DEBUG 时调用 console.groupEnd
75
+ ```
76
+
77
+ ### `setLevel(level)` / `getLevel()`
78
+
79
+ 运行时修改或读取日志级别:
80
+
81
+ ```ts
82
+ logger.setLevel(Logger.LEVEL.DEBUG); // 开启所有日志
83
+ logger.setLevel(Logger.LEVEL.NONE); // 关闭所有日志
84
+
85
+ console.log(logger.getLevel()); // 0
86
+ ```
87
+
88
+ ### `getLogger(debug?)`
89
+
90
+ 返回全局单例 logger,前缀固定为 `"Logger"`:
91
+
92
+ ```ts
93
+ import { getLogger } from "@skax/logger";
94
+
95
+ const log = getLogger(true); // DEBUG 级别
96
+ log.info("应用已初始化"); // → [Logger] [INFO] 应用已初始化
97
+ ```
98
+
99
+ 单例在首次调用时惰性创建——后续调用返回同一实例。
100
+
101
+ ### TypeScript
102
+
103
+ ```ts
104
+ import { Logger } from "@skax/logger";
105
+
106
+ // 级别类型从 Logger.LEVEL 推导:
107
+ const level: (typeof Logger.LEVEL)[keyof typeof Logger.LEVEL] = Logger.LEVEL.DEBUG;
108
+
109
+ // 或直接让 TS 推断:
110
+ const logger = new Logger("TSModule", Logger.LEVEL.INFO);
111
+ logger.setLevel(Logger.LEVEL.DEBUG);
112
+ const current = logger.getLevel(); // 0 | 1 | 2 | 3 | 4
113
+ ```
114
+
115
+ ## 原理
116
+
117
+ 构造函数返回一个 **Proxy** 实例来拦截属性访问。调用 `logger.info(...)` 时:
118
+
119
+ 1. Proxy 的 `get` 陷阱检查 `target._level >= Logger.LEVEL.INFO`
120
+ 2. 满足条件 → 返回 `console.info.bind(console, "[前缀] [INFO]")` — 在**调用者**栈帧中执行
121
+ 3. 不满足 → 返回 `Logger.NOOP` — 空函数,零开销
122
+
123
+ ```
124
+ yourFile.ts:42 → logger.info("你好")
125
+
126
+ Proxy.get("info")
127
+
128
+ console.info.bind(console, "[Demo] [INFO]")
129
+
130
+ DevTools 源链接 → yourFile.ts:42 ✓
131
+ ```
132
+
133
+ ## 浏览器使用 (UMD)
134
+
135
+ ```html
136
+ <script src="./node_modules/@skax/logger/dist/index.umd.js"></script>
137
+ <script>
138
+ const logger = new Logger("Browser", Logger.LEVEL.DEBUG);
139
+ logger.info("来自浏览器的问候!");
140
+ </script>
141
+ ```
142
+
143
+ 在线演示:[`public/index.html`](public/index.html)
144
+
145
+ ## 构建
146
+
147
+ ```bash
148
+ npm run build # 生产构建(CJS + ESM + UMD)
149
+ npm run dev # 开发模式(watch)
150
+ npm run test # 运行测试(含覆盖率)
151
+ ```
152
+
153
+ 输出结构:
154
+
155
+ ```
156
+ dist/
157
+ ├── index.cjs # CommonJS
158
+ ├── index.esm.js # ES Module
159
+ ├── index.umd.js # UMD(浏览器)
160
+ └── types/
161
+ └── index.d.ts # TypeScript 类型声明
162
+ ```
163
+
164
+ ## 许可证
165
+
166
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,6 @@
1
+ /*
2
+ * @skax/logger v2.0.0-beta.1
3
+ * Copyright (c) 2026-05-16 ShineShao <xiaoshaoqq@gmail.com>
4
+ * Released under the MIT License.
5
+ */
6
+ "use strict";var Logger=function(){function Logger(prefix,level){if(void 0===prefix&&(prefix="Logger"),void 0===level&&(level=Logger.LEVEL.WARN),this._prefix=prefix,this._level=level,"function"==typeof Proxy&&"object"==("undefined"==typeof Reflect?"undefined":(obj=Reflect)&&"undefined"!=typeof Symbol&&obj.constructor===Symbol?"symbol":typeof obj))return new Proxy(this,{get:function(target,prop,receiver){var value=Reflect.get(target,prop,receiver);if("setLevel"===prop||"getLevel"===prop)return"function"==typeof value?value.bind(target):value;if("string"==typeof prop&&prop.startsWith("_"))return value;switch(prop){case"error":return target._level>=Logger.LEVEL.ERROR?function(){}.bind():Logger.NOOP;case"warn":return target._level>=Logger.LEVEL.WARN?function(){}.bind():Logger.NOOP;case"info":return target._level>=Logger.LEVEL.INFO?function(){}.bind():Logger.NOOP;case"debug":case"group":case"groupEnd":return target._level>=Logger.LEVEL.DEBUG?function(){}.bind():Logger.NOOP;default:return value}}});var obj}var _proto=Logger.prototype;return _proto.setLevel=function(level){this._level=level},_proto.getLevel=function(){return this._level},_proto.error=function(){for(var _len=arguments.length,_args=new Array(_len),_key=0;_key<_len;_key++)_args[_key]=arguments[_key];var _console;this._level>=Logger.LEVEL.ERROR&&(_console=console).error.apply(_console,[].concat(["["+this._prefix+"] [ERROR]"],_args))},_proto.warn=function(){for(var _len=arguments.length,_args=new Array(_len),_key=0;_key<_len;_key++)_args[_key]=arguments[_key];var _console;this._level>=Logger.LEVEL.WARN&&(_console=console).warn.apply(_console,[].concat(["["+this._prefix+"] [WARN]"],_args))},_proto.info=function(){for(var _len=arguments.length,_args=new Array(_len),_key=0;_key<_len;_key++)_args[_key]=arguments[_key];var _console;this._level>=Logger.LEVEL.INFO&&(_console=console).info.apply(_console,[].concat(["["+this._prefix+"] [INFO]"],_args))},_proto.debug=function(){for(var _len=arguments.length,_args=new Array(_len),_key=0;_key<_len;_key++)_args[_key]=arguments[_key];var _console;this._level>=Logger.LEVEL.DEBUG&&(_console=console).debug.apply(_console,[].concat(["["+this._prefix+"] [DEBUG]"],_args))},_proto.group=function(_label){this._level,Logger.LEVEL.DEBUG},_proto.groupEnd=function(){this._level,Logger.LEVEL.DEBUG},Logger}();Logger.NOOP=function(){},Logger.LEVEL={NONE:0,ERROR:1,WARN:2,INFO:3,DEBUG:4};var __$Default_Logger$__=null;exports.Logger=Logger,exports.getLogger=function(debug){return void 0===debug&&(debug=!1),__$Default_Logger$__||(__$Default_Logger$__=new Logger("Logger",debug?Logger.LEVEL.DEBUG:Logger.LEVEL.WARN)),__$Default_Logger$__};
@@ -0,0 +1,6 @@
1
+ /*
2
+ * @skax/logger v2.0.0-beta.1
3
+ * Copyright (c) 2026-05-16 ShineShao <xiaoshaoqq@gmail.com>
4
+ * Released under the MIT License.
5
+ */
6
+ var Logger=function(){function Logger(prefix,level){if(void 0===prefix&&(prefix="Logger"),void 0===level&&(level=Logger.LEVEL.WARN),this._prefix=prefix,this._level=level,"function"==typeof Proxy&&"object"==("undefined"==typeof Reflect?"undefined":(obj=Reflect)&&"undefined"!=typeof Symbol&&obj.constructor===Symbol?"symbol":typeof obj))return new Proxy(this,{get:function(target,prop,receiver){var value=Reflect.get(target,prop,receiver);if("setLevel"===prop||"getLevel"===prop)return"function"==typeof value?value.bind(target):value;if("string"==typeof prop&&prop.startsWith("_"))return value;switch(prop){case"error":return target._level>=Logger.LEVEL.ERROR?function(){}.bind():Logger.NOOP;case"warn":return target._level>=Logger.LEVEL.WARN?function(){}.bind():Logger.NOOP;case"info":return target._level>=Logger.LEVEL.INFO?function(){}.bind():Logger.NOOP;case"debug":case"group":case"groupEnd":return target._level>=Logger.LEVEL.DEBUG?function(){}.bind():Logger.NOOP;default:return value}}});var obj}var _proto=Logger.prototype;return _proto.setLevel=function(level){this._level=level},_proto.getLevel=function(){return this._level},_proto.error=function(){for(var _len=arguments.length,_args=new Array(_len),_key=0;_key<_len;_key++)_args[_key]=arguments[_key];var _console;this._level>=Logger.LEVEL.ERROR&&(_console=console).error.apply(_console,[].concat(["["+this._prefix+"] [ERROR]"],_args))},_proto.warn=function(){for(var _len=arguments.length,_args=new Array(_len),_key=0;_key<_len;_key++)_args[_key]=arguments[_key];var _console;this._level>=Logger.LEVEL.WARN&&(_console=console).warn.apply(_console,[].concat(["["+this._prefix+"] [WARN]"],_args))},_proto.info=function(){for(var _len=arguments.length,_args=new Array(_len),_key=0;_key<_len;_key++)_args[_key]=arguments[_key];var _console;this._level>=Logger.LEVEL.INFO&&(_console=console).info.apply(_console,[].concat(["["+this._prefix+"] [INFO]"],_args))},_proto.debug=function(){for(var _len=arguments.length,_args=new Array(_len),_key=0;_key<_len;_key++)_args[_key]=arguments[_key];var _console;this._level>=Logger.LEVEL.DEBUG&&(_console=console).debug.apply(_console,[].concat(["["+this._prefix+"] [DEBUG]"],_args))},_proto.group=function(_label){this._level,Logger.LEVEL.DEBUG},_proto.groupEnd=function(){this._level,Logger.LEVEL.DEBUG},Logger}();Logger.NOOP=function(){},Logger.LEVEL={NONE:0,ERROR:1,WARN:2,INFO:3,DEBUG:4};var __$Default_Logger$__=null;function getLogger(debug){return void 0===debug&&(debug=!1),__$Default_Logger$__||(__$Default_Logger$__=new Logger("Logger",debug?Logger.LEVEL.DEBUG:Logger.LEVEL.WARN)),__$Default_Logger$__}export{Logger,getLogger};
@@ -0,0 +1,6 @@
1
+ /*
2
+ * @skax/logger v2.0.0-beta.1
3
+ * Copyright (c) 2026-05-16 ShineShao <xiaoshaoqq@gmail.com>
4
+ * Released under the MIT License.
5
+ */
6
+ !function(global,factory){"object"==typeof exports&&"undefined"!=typeof module?module.exports=factory():"function"==typeof define&&define.amd?define(factory):(global="undefined"!=typeof globalThis?globalThis:global||self).Logger=factory()}(this,function(){"use strict";var Logger=function(){function Logger(prefix,level){if(void 0===prefix&&(prefix="Logger"),void 0===level&&(level=Logger.LEVEL.WARN),this._prefix=prefix,this._level=level,"function"==typeof Proxy&&"object"==("undefined"==typeof Reflect?"undefined":(obj=Reflect)&&"undefined"!=typeof Symbol&&obj.constructor===Symbol?"symbol":typeof obj))return new Proxy(this,{get:function(target,prop,receiver){var value=Reflect.get(target,prop,receiver);if("setLevel"===prop||"getLevel"===prop)return"function"==typeof value?value.bind(target):value;if("string"==typeof prop&&prop.startsWith("_"))return value;switch(prop){case"error":return target._level>=Logger.LEVEL.ERROR?function(){}.bind():Logger.NOOP;case"warn":return target._level>=Logger.LEVEL.WARN?function(){}.bind():Logger.NOOP;case"info":return target._level>=Logger.LEVEL.INFO?function(){}.bind():Logger.NOOP;case"debug":case"group":case"groupEnd":return target._level>=Logger.LEVEL.DEBUG?function(){}.bind():Logger.NOOP;default:return value}}});var obj}var _proto=Logger.prototype;return _proto.setLevel=function(level){this._level=level},_proto.getLevel=function(){return this._level},_proto.error=function(){for(var _len=arguments.length,_args=new Array(_len),_key=0;_key<_len;_key++)_args[_key]=arguments[_key];var _console;this._level>=Logger.LEVEL.ERROR&&(_console=console).error.apply(_console,[].concat(["["+this._prefix+"] [ERROR]"],_args))},_proto.warn=function(){for(var _len=arguments.length,_args=new Array(_len),_key=0;_key<_len;_key++)_args[_key]=arguments[_key];var _console;this._level>=Logger.LEVEL.WARN&&(_console=console).warn.apply(_console,[].concat(["["+this._prefix+"] [WARN]"],_args))},_proto.info=function(){for(var _len=arguments.length,_args=new Array(_len),_key=0;_key<_len;_key++)_args[_key]=arguments[_key];var _console;this._level>=Logger.LEVEL.INFO&&(_console=console).info.apply(_console,[].concat(["["+this._prefix+"] [INFO]"],_args))},_proto.debug=function(){for(var _len=arguments.length,_args=new Array(_len),_key=0;_key<_len;_key++)_args[_key]=arguments[_key];var _console;this._level>=Logger.LEVEL.DEBUG&&(_console=console).debug.apply(_console,[].concat(["["+this._prefix+"] [DEBUG]"],_args))},_proto.group=function(_label){this._level,Logger.LEVEL.DEBUG},_proto.groupEnd=function(){this._level,Logger.LEVEL.DEBUG},Logger}();return Logger.NOOP=function(){},Logger.LEVEL={NONE:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},Logger});
@@ -0,0 +1,260 @@
1
+ /**
2
+ * Lightweight logger with level filtering, module prefix, and caller-context output.
3
+ *
4
+ * Uses Proxy + Reflect so that `console.error/warn/info/debug` are invoked in the
5
+ * **caller's** stack frame, not inside logger.ts. The browser DevTools source link
6
+ * will point to the actual call site (e.g. `fetcher.ts:411`) rather than
7
+ * `logger.ts:140`.
8
+ *
9
+ * 轻量级日志工具,支持分级过滤、模块前缀、调用者上下文输出。
10
+ *
11
+ * 通过 Proxy + Reflect 使得 `console.error/warn/info/debug` 在**调用者**的
12
+ * 栈帧中执行。浏览器 DevTools 的源文件链接会指向真正的调用位置
13
+ * (如 `fetcher.ts:411`),而不是 `logger.ts:140`。
14
+ *
15
+ * @module
16
+ * @example
17
+ * ```ts
18
+ * import { Logger } from "@skax/logger";
19
+ *
20
+ * const logger = new Logger("MyModule", Logger.LEVEL.DEBUG);
21
+ * logger.info("服务启动", { port: 3000 });
22
+ * // [MyModule] [INFO] 服务启动 { port: 3000 }
23
+ * // ↑ DevTools source: the actual file that called logger.info
24
+ * ```
25
+ */
26
+ /**
27
+ * 日志记录器。
28
+ *
29
+ * 构造时返回 Proxy 实例,对 `logger.xxx()` 的每次调用都在**调用者**的栈帧中执行
30
+ * `console.xxx`,因此浏览器 DevTools 的源文件链接指向业务代码而非本文件。
31
+ *
32
+ * 当 Proxy 不可用时(如极端旧环境),降级为普通方法调用。
33
+ *
34
+ * @class
35
+ * @example
36
+ * ```ts
37
+ * const logger = new Logger("Logger");
38
+ * logger.info("playlist loaded");
39
+ * ```
40
+ */
41
+ declare class Logger {
42
+ /**
43
+ * 空函数,当日志级别不满足条件时替代真正的 console 方法,避免无效调用。
44
+ *
45
+ * 每个被抑制的日志方法调用都会返回此函数,调用者执行它时不会有任何副作用。
46
+ *
47
+ * Empty function used as noop when the log level suppresses output.
48
+ * Every suppressed log method returns this function — calling it is a true no-op.
49
+ *
50
+ * @public
51
+ */
52
+ static NOOP: () => void;
53
+ /**
54
+ * 日志等级常量(数字枚举对象)。
55
+ *
56
+ * 使用 `as const` 断言保留字面量类型,便于 TS 推导出联合类型
57
+ * `0 | 1 | 2 | 3 | 4`,同时作为静态属性暴露供外部使用。
58
+ *
59
+ * | 常量 | 值 | 说明 |
60
+ * |------|----|------|
61
+ * | `Logger.LEVEL.NONE` | `0` | 关闭所有日志 |
62
+ * | `Logger.LEVEL.ERROR` | `1` | 仅输出 error |
63
+ * | `Logger.LEVEL.WARN` | `2` | 输出 warn 及更高级别 |
64
+ * | `Logger.LEVEL.INFO` | `3` | 输出 info 及更高级别 |
65
+ * | `Logger.LEVEL.DEBUG` | `4` | 输出所有日志(含 debug) |
66
+ *
67
+ * Log level constants declared with `as const` so TypeScript
68
+ * infers literal types, enabling the union `0 | 1 | 2 | 3 | 4`.
69
+ *
70
+ * | Constant | Value | Description |
71
+ * |----------|-------|-------------|
72
+ * | `Logger.LEVEL.NONE` | `0` | Suppress all output |
73
+ * | `Logger.LEVEL.ERROR` | `1` | Only errors |
74
+ * | `Logger.LEVEL.WARN` | `2` | Warnings and above |
75
+ * | `Logger.LEVEL.INFO` | `3` | Info and above |
76
+ * | `Logger.LEVEL.DEBUG` | `4` | All messages (including debug) |
77
+ *
78
+ * @public
79
+ */
80
+ static LEVEL: {
81
+ /** 关闭所有日志 */
82
+ readonly NONE: 0;
83
+ /** 仅输出 error */
84
+ readonly ERROR: 1;
85
+ /** 输出 warn 及更高级别 */
86
+ readonly WARN: 2;
87
+ /** 输出 info 及更高级别 */
88
+ readonly INFO: 3;
89
+ /** 输出所有日志(含 debug) */
90
+ readonly DEBUG: 4;
91
+ };
92
+ /**
93
+ * 当前日志级别。只有 ≥ 此级别的日志方法才会真正输出。
94
+ *
95
+ * @private
96
+ */
97
+ private _level;
98
+ /**
99
+ * 模块前缀,显示在每条日志的 `[前缀]` 中,用于区分不同模块的输出。
100
+ *
101
+ * @private
102
+ */
103
+ private _prefix;
104
+ /**
105
+ * 创建一个 Logger 实例。
106
+ *
107
+ * 在支持 Proxy 的环境中,构造函数返回 Proxy 实例而非 `this`。
108
+ * Proxy 拦截所有属性访问,按需返回绑定了前缀的 `console.*` 函数或空函数。
109
+ *
110
+ * @param {string} [prefix="Logger"] - 模块前缀,显示在 `[方括号]` 中
111
+ * @param {number} [level=Logger.LEVEL.WARN] - 最低输出级别,低于此级别的日志会被抑制
112
+ *
113
+ * @example
114
+ * ```ts
115
+ * // 默认 WARN 级别,只输出 error 和 warn
116
+ * const logger = new Logger("Logger");
117
+ *
118
+ * // DEBUG 级别,输出所有日志
119
+ * const debugLogger = new Logger("Debug", Logger.LEVEL.DEBUG);
120
+ * ```
121
+ */
122
+ constructor(prefix?: string, level?: (typeof Logger.LEVEL)[keyof typeof Logger.LEVEL]);
123
+ /**
124
+ * 动态设置日志级别。
125
+ *
126
+ * 调用后立即生效——已抑制的日志方法会变为 NOOP,已启用的会恢复输出。
127
+ *
128
+ * @param {number} level - 新的日志级别,使用 `Logger.LEVEL.XXX` 常量
129
+ *
130
+ * @example
131
+ * ```ts
132
+ * logger.setLevel(Logger.LEVEL.DEBUG); // 开启全部日志
133
+ * logger.setLevel(Logger.LEVEL.NONE); // 关闭全部日志
134
+ * ```
135
+ */
136
+ setLevel(level: (typeof Logger.LEVEL)[keyof typeof Logger.LEVEL]): void;
137
+ /**
138
+ * 获取当前日志级别。
139
+ *
140
+ * @returns {number} 当前日志级别(0 | 1 | 2 | 3 | 4)
141
+ *
142
+ * @example
143
+ * ```ts
144
+ * if (logger.getLevel() === Logger.LEVEL.DEBUG) {
145
+ * logger.info("调试模式已开启");
146
+ * }
147
+ * ```
148
+ */
149
+ getLevel(): (typeof Logger.LEVEL)[keyof typeof Logger.LEVEL];
150
+ /**
151
+ * 输出错误日志。
152
+ *
153
+ * 当 `level ≥ ERROR` 时输出到 `console.error`,带 `[prefix] [ERROR]` 前缀。
154
+ *
155
+ * @param {...unknown} _args - 任意参数,原样传递给 console.error
156
+ *
157
+ * @example
158
+ * ```ts
159
+ * logger.error("请求失败", { status: 500 });
160
+ * // → [Logger] [ERROR] 请求失败 { status: 500 }
161
+ * ```
162
+ */
163
+ error(..._args: unknown[]): void;
164
+ /**
165
+ * 输出警告日志。
166
+ *
167
+ * 当 `level ≥ WARN` 时输出到 `console.warn`,带 `[prefix] [WARN]` 前缀。
168
+ *
169
+ * @param {...unknown} _args - 任意参数
170
+ *
171
+ * @example
172
+ * ```ts
173
+ * logger.warn("配置项缺失,使用默认值", { key: "timeout" });
174
+ * // → [Logger] [WARN] 配置项缺失,使用默认值 { key: "timeout" }
175
+ * ```
176
+ */
177
+ warn(..._args: unknown[]): void;
178
+ /**
179
+ * 输出信息日志。
180
+ *
181
+ * 当 `level ≥ INFO` 时输出到 `console.info`,带 `[prefix] [INFO]` 前缀。
182
+ *
183
+ * @param {...unknown} _args - 任意参数
184
+ *
185
+ * @example
186
+ * ```ts
187
+ * logger.info("服务启动", { port: 3000 });
188
+ * // → [Logger] [INFO] 服务启动 { port: 3000 }
189
+ * ```
190
+ */
191
+ info(..._args: unknown[]): void;
192
+ /**
193
+ * 输出调试日志。
194
+ *
195
+ * 当 `level ≥ DEBUG` 时输出到 `console.debug`,带 `[prefix] [DEBUG]` 前缀。
196
+ *
197
+ * @param {...unknown} _args - 任意参数
198
+ *
199
+ * @example
200
+ * ```ts
201
+ * logger.debug("请求详情", { method: "POST", payload: { id: 1 } });
202
+ * // → [Logger] [DEBUG] 请求详情 { method: "POST", payload: { id: 1 } }
203
+ * ```
204
+ */
205
+ debug(..._args: unknown[]): void;
206
+ /**
207
+ * 开始一个可折叠的日志分组(浏览器 console.group)。
208
+ *
209
+ * 当 `level ≥ DEBUG` 时调用 `console.group`,此后直到 `groupEnd()` 的日志
210
+ * 会嵌套在该分组内。
211
+ *
212
+ * @param {string} _label - 分组标题
213
+ *
214
+ * @example
215
+ * ```ts
216
+ * logger.group("批量处理");
217
+ * logger.debug("步骤 1");
218
+ * logger.debug("步骤 2");
219
+ * logger.groupEnd();
220
+ * ```
221
+ */
222
+ group(_label: string): void;
223
+ /**
224
+ * 结束当前日志分组(浏览器 console.groupEnd)。
225
+ *
226
+ * 当 `level ≥ DEBUG` 时调用 `console.groupEnd`。
227
+ *
228
+ * @example
229
+ * ```ts
230
+ * logger.groupEnd();
231
+ * ```
232
+ */
233
+ groupEnd(): void;
234
+ }
235
+ /**
236
+ * 获取全局共享的 Logger 单例。
237
+ *
238
+ * 惰性初始化:首次调用时创建实例,后续调用返回同一对象。
239
+ * 前缀固定为 `"Logger"`。
240
+ *
241
+ * @param {boolean} [debug=false] - 是否开启 DEBUG 模式。`true` 时级别为 DEBUG,否则为 WARN
242
+ * @returns {Logger} 全局唯一的 Logger 实例
243
+ *
244
+ * @example
245
+ * ```ts
246
+ * import { getLogger } from "@skax/logger";
247
+ *
248
+ * // 生产环境:默认 WARN 级别
249
+ * const log = getLogger();
250
+ *
251
+ * // 开发环境:DEBUG 级别
252
+ * const debugLog = getLogger(true);
253
+ *
254
+ * // 两次调用返回同一实例
255
+ * console.log(getLogger() === getLogger()); // true
256
+ * ```
257
+ */
258
+ declare function getLogger(debug?: boolean): Logger;
259
+
260
+ export { Logger, getLogger };
package/package.json CHANGED
@@ -1,25 +1,78 @@
1
1
  {
2
2
  "name": "@skax/logger",
3
- "version": "1.0.1",
4
- "description": "console logger",
5
- "main": "index.js",
6
- "umd": "index.umd.js",
7
- "types": "types/index.d.ts",
8
- "repository": {
9
- "type": "git",
10
- "url": "git+https://github.com/freeshineit/skax-logger.git"
3
+ "version": "2.0.0-beta.1",
4
+ "description": "A lightweight logger with level filtering, module prefix, and caller-context output.",
5
+ "main": "dist/index.cjs",
6
+ "module": "dist/index.esm.js",
7
+ "types": "dist/types/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/types/index.d.ts",
11
+ "import": "./dist/index.esm.js",
12
+ "require": "./dist/index.cjs",
13
+ "default": "./dist/index.cjs"
14
+ },
15
+ "./dist/index.umd.js": "./dist/index.umd.js",
16
+ "./dist/index.umd": "./dist/index.umd.js"
17
+ },
18
+ "files": [
19
+ "dist"
20
+ ],
21
+ "scripts": {
22
+ "dev": "npm run clean && cross-env NODE_ENV=development rollup --config rollup.config.mjs --watch",
23
+ "build": "npm run clean && cross-env NODE_ENV=production rollup --config rollup.config.mjs",
24
+ "clean": "rimraf dist",
25
+ "test": "jest --coverage",
26
+ "test:watch": "jest --watch",
27
+ "lint": "eslint --fix \"./src/**/*.{ts,tsx,js,jsx,mjs,vue,cjs}\"",
28
+ "lint:check": "eslint \"./src/**/*.{ts,tsx,js,jsx,mjs,vue,cjs}\"",
29
+ "fmt": "prettier --write \"./**/*.{ts,tsx,js,jsx,mjs,json,md,yml,yaml,vue,cjs,css,scss,sass}\"",
30
+ "fmt:check": "prettier --check \"./**/*.{ts,tsx,js,jsx,mjs,json,md,yml,yaml,vue,cjs,css,scss,sass}\"",
31
+ "docs": "typedoc",
32
+ "prepare": "husky"
11
33
  },
12
34
  "keywords": [
13
35
  "logger",
14
- "console"
36
+ "logging",
37
+ "debug",
38
+ "info",
39
+ "warn",
40
+ "error",
41
+ "typescript",
42
+ "javascript"
15
43
  ],
16
44
  "author": "ShineShao <xiaoshaoqq@gmail.com>",
17
45
  "license": "MIT",
46
+ "devDependencies": {
47
+ "@commitlint/cli": "^20.2.0",
48
+ "@commitlint/config-conventional": "^20.2.0",
49
+ "pretty-quick": "^4.2.2",
50
+ "@skax/rollup-config": "^1.0.2",
51
+ "@types/jest": "^29.5.11",
52
+ "cross-env": "^10.1.0",
53
+ "eslint": "^9.39.4",
54
+ "eslint-config-xx": "^2.2.4",
55
+ "http-server": "^14.1.1",
56
+ "husky": "^9.1.7",
57
+ "jest": "^29.7.0",
58
+ "jest-environment-jsdom": "^29.7.0",
59
+ "prettier": "^3.8.1",
60
+ "rimraf": "^6.1.2",
61
+ "rollup": "^4.60.2",
62
+ "ts-jest": "^29.1.1",
63
+ "tslib": "^2.6.2",
64
+ "typedoc": "^0.28.14",
65
+ "typedoc-plugin-mdn-links": "^5.0.10",
66
+ "typedoc-plugin-rename-defaults": "^0.7.3",
67
+ "typedoc-plugin-replace-text": "^4.2.0",
68
+ "typescript": "^5.9.3"
69
+ },
70
+ "repository": {
71
+ "type": "git",
72
+ "url": "git+https://github.com/freeshineit/logger.git"
73
+ },
18
74
  "bugs": {
19
- "url": "https://github.com/freeshineit/skax-logger/issues"
75
+ "url": "https://github.com/freeshineit/logger/issues"
20
76
  },
21
- "homepage": "https://github.com/freeshineit/skax-logger#readme",
22
- "engines": {
23
- "node": ">=16"
24
- }
25
- }
77
+ "homepage": "https://github.com/freeshineit/logger#readme"
78
+ }
package/index.js DELETED
@@ -1,162 +0,0 @@
1
- /*
2
- *
3
- * @skax/logger.js v1.0.1
4
- * Copyright (c) 2023-9-30 ShineShao <xiaoshaoqq@gmail.com>
5
- * Released under the MIT License.
6
- *
7
- */
8
- 'use strict';
9
-
10
- /**
11
- * @class Logger
12
- * @classdesc Provide multiple log printing methods
13
- * @example
14
- * const logger = new Logger({})
15
- * logger.v("verbose log")
16
- */
17
- var Logger = /** @class */ (function () {
18
- function Logger(options) {
19
- if (options === void 0) { options = {}; }
20
- this._options = {};
21
- this._levelNum = 0;
22
- /**
23
- * @description Method used to print error logs
24
- * @method
25
- *
26
- * @example
27
- * logger.e("error message") // error message
28
- *
29
- * @param {...any[]} args error messages
30
- * @returns {void}
31
- */
32
- this.e = this._loggerFactory('error', this._levelNum <= 4);
33
- /**
34
- * @description Method used to print warn logs
35
- * @method
36
- *
37
- * @example
38
- * logger.w("warn message") // warn message
39
- *
40
- * @param {...any[]} args warn messages
41
- * @returns {void}
42
- */
43
- this.w = this._loggerFactory('warn', this._levelNum <= 3);
44
- /**
45
- * @description Method used to print info logs
46
- * @method
47
- *
48
- * @example
49
- * logger.i("info message") // info message
50
- *
51
- * @param {...any[]} args info messages
52
- * @returns {void}
53
- */
54
- this.i = this._loggerFactory('info', this._levelNum <= 2);
55
- /**
56
- * @description Method used to print verbose logs
57
- * @method
58
- *
59
- * @example
60
- * logger.v("verbose message") // verbose message
61
- *
62
- * @param {...any[]} args verbose messages
63
- * @returns {void}
64
- */
65
- this.v = this._loggerFactory('log', this._levelNum <= 1);
66
- /**
67
- * @description Method used to print debug logs
68
- * @method
69
- *
70
- * @example
71
- * logger.d("debug message") // debug message
72
- *
73
- * @param {...any[]} msg debug messages
74
- * @returns {void}
75
- */
76
- this.d = this._loggerFactory('debug', this._levelNum < 1);
77
- this.setOptions(options);
78
- }
79
- /**
80
- * @description Method used to set logger option and change logger level
81
- *
82
- * @example
83
- * logger.setOptions({level: 'INFO'}) // set logger level
84
- *
85
- * @param {LoggerOptions} options logger options
86
- * @return {void}
87
- */
88
- Logger.prototype.setOptions = function (options) {
89
- this._options = options;
90
- this._levelNum = this._matchLevel(options.level || 'DEBUG');
91
- if (this._levelNum !== 0) {
92
- this.e = this._loggerFactory('error', this._levelNum <= 4);
93
- this.w = this._loggerFactory('warn', this._levelNum <= 3);
94
- this.i = this._loggerFactory('info', this._levelNum <= 2);
95
- this.v = this._loggerFactory('log', this._levelNum <= 1);
96
- this.d = this._loggerFactory('warn', this._levelNum < 1);
97
- }
98
- };
99
- /**
100
- * @description Private method used to match logger level
101
- * @private
102
- *
103
- * @example
104
- * this._matchLevel("DEBUG") // 0
105
- *
106
- * @param {LoggerLevel} level logger level
107
- * @return {number}
108
- */
109
- Logger.prototype._matchLevel = function (level) {
110
- var logLevel = 0;
111
- switch (level) {
112
- case 'DEBUG':
113
- logLevel = 0;
114
- break;
115
- case 'VERBOSE':
116
- logLevel = 1;
117
- break;
118
- case 'INFO':
119
- logLevel = 2;
120
- break;
121
- case 'WARN':
122
- logLevel = 3;
123
- break;
124
- case 'ERROR':
125
- logLevel = 4;
126
- break;
127
- }
128
- return logLevel;
129
- };
130
- /**
131
- * @private
132
- * @description Logger factory
133
- * @param {ConsoleKey} type
134
- * @param {boolean} bool
135
- * @returns
136
- */
137
- Logger.prototype._loggerFactory = function (type, bool) {
138
- var func = console[type];
139
- if (bool && func) {
140
- return func.bind(console, "[".concat(type.toLocaleUpperCase(), "]"));
141
- }
142
- return Logger.noop;
143
- };
144
- /**
145
- * @description Get options
146
- * @returns {LoggerOptions}
147
- */
148
- Logger.prototype.getOptions = function () {
149
- return this._options;
150
- };
151
- /**
152
- * @description Get version
153
- * @returns {string}
154
- */
155
- Logger.prototype.version = function () {
156
- return '1.0.1';
157
- };
158
- Logger.noop = function () { };
159
- return Logger;
160
- }());
161
-
162
- module.exports = Logger;
package/index.umd.js DELETED
@@ -1,168 +0,0 @@
1
- /*
2
- *
3
- * @skax/logger.js v1.0.1
4
- * Copyright (c) 2023-9-30 ShineShao <xiaoshaoqq@gmail.com>
5
- * Released under the MIT License.
6
- *
7
- */
8
- (function (global, factory) {
9
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
10
- typeof define === 'function' && define.amd ? define(factory) :
11
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Logger = factory());
12
- })(this, (function () { 'use strict';
13
-
14
- /**
15
- * @class Logger
16
- * @classdesc Provide multiple log printing methods
17
- * @example
18
- * const logger = new Logger({})
19
- * logger.v("verbose log")
20
- */
21
- var Logger = /** @class */ (function () {
22
- function Logger(options) {
23
- if (options === void 0) { options = {}; }
24
- this._options = {};
25
- this._levelNum = 0;
26
- /**
27
- * @description Method used to print error logs
28
- * @method
29
- *
30
- * @example
31
- * logger.e("error message") // error message
32
- *
33
- * @param {...any[]} args error messages
34
- * @returns {void}
35
- */
36
- this.e = this._loggerFactory('error', this._levelNum <= 4);
37
- /**
38
- * @description Method used to print warn logs
39
- * @method
40
- *
41
- * @example
42
- * logger.w("warn message") // warn message
43
- *
44
- * @param {...any[]} args warn messages
45
- * @returns {void}
46
- */
47
- this.w = this._loggerFactory('warn', this._levelNum <= 3);
48
- /**
49
- * @description Method used to print info logs
50
- * @method
51
- *
52
- * @example
53
- * logger.i("info message") // info message
54
- *
55
- * @param {...any[]} args info messages
56
- * @returns {void}
57
- */
58
- this.i = this._loggerFactory('info', this._levelNum <= 2);
59
- /**
60
- * @description Method used to print verbose logs
61
- * @method
62
- *
63
- * @example
64
- * logger.v("verbose message") // verbose message
65
- *
66
- * @param {...any[]} args verbose messages
67
- * @returns {void}
68
- */
69
- this.v = this._loggerFactory('log', this._levelNum <= 1);
70
- /**
71
- * @description Method used to print debug logs
72
- * @method
73
- *
74
- * @example
75
- * logger.d("debug message") // debug message
76
- *
77
- * @param {...any[]} msg debug messages
78
- * @returns {void}
79
- */
80
- this.d = this._loggerFactory('debug', this._levelNum < 1);
81
- this.setOptions(options);
82
- }
83
- /**
84
- * @description Method used to set logger option and change logger level
85
- *
86
- * @example
87
- * logger.setOptions({level: 'INFO'}) // set logger level
88
- *
89
- * @param {LoggerOptions} options logger options
90
- * @return {void}
91
- */
92
- Logger.prototype.setOptions = function (options) {
93
- this._options = options;
94
- this._levelNum = this._matchLevel(options.level || 'DEBUG');
95
- if (this._levelNum !== 0) {
96
- this.e = this._loggerFactory('error', this._levelNum <= 4);
97
- this.w = this._loggerFactory('warn', this._levelNum <= 3);
98
- this.i = this._loggerFactory('info', this._levelNum <= 2);
99
- this.v = this._loggerFactory('log', this._levelNum <= 1);
100
- this.d = this._loggerFactory('warn', this._levelNum < 1);
101
- }
102
- };
103
- /**
104
- * @description Private method used to match logger level
105
- * @private
106
- *
107
- * @example
108
- * this._matchLevel("DEBUG") // 0
109
- *
110
- * @param {LoggerLevel} level logger level
111
- * @return {number}
112
- */
113
- Logger.prototype._matchLevel = function (level) {
114
- var logLevel = 0;
115
- switch (level) {
116
- case 'DEBUG':
117
- logLevel = 0;
118
- break;
119
- case 'VERBOSE':
120
- logLevel = 1;
121
- break;
122
- case 'INFO':
123
- logLevel = 2;
124
- break;
125
- case 'WARN':
126
- logLevel = 3;
127
- break;
128
- case 'ERROR':
129
- logLevel = 4;
130
- break;
131
- }
132
- return logLevel;
133
- };
134
- /**
135
- * @private
136
- * @description Logger factory
137
- * @param {ConsoleKey} type
138
- * @param {boolean} bool
139
- * @returns
140
- */
141
- Logger.prototype._loggerFactory = function (type, bool) {
142
- var func = console[type];
143
- if (bool && func) {
144
- return func.bind(console, "[".concat(type.toLocaleUpperCase(), "]"));
145
- }
146
- return Logger.noop;
147
- };
148
- /**
149
- * @description Get options
150
- * @returns {LoggerOptions}
151
- */
152
- Logger.prototype.getOptions = function () {
153
- return this._options;
154
- };
155
- /**
156
- * @description Get version
157
- * @returns {string}
158
- */
159
- Logger.prototype.version = function () {
160
- return '1.0.1';
161
- };
162
- Logger.noop = function () { };
163
- return Logger;
164
- }());
165
-
166
- return Logger;
167
-
168
- }));
package/types/index.d.ts DELETED
@@ -1,116 +0,0 @@
1
- /** logger level */
2
- export type LoggerLevel = 'DEBUG' | 'VERBOSE' | 'INFO' | 'WARN' | 'ERROR';
3
- /** logger options */
4
- export interface LoggerOptions {
5
- /** logger level */
6
- level?: LoggerLevel;
7
- }
8
- export type LoggerFunc = (...data: any[]) => void;
9
- /**
10
- * @class Logger
11
- * @classdesc Provide multiple log printing methods
12
- * @example
13
- * const logger = new Logger({})
14
- * logger.v("verbose log")
15
- */
16
- declare class Logger {
17
- private static readonly noop;
18
- private _options;
19
- private _levelNum;
20
- constructor(options?: LoggerOptions);
21
- /**
22
- * @description Method used to print error logs
23
- * @method
24
- *
25
- * @example
26
- * logger.e("error message") // error message
27
- *
28
- * @param {...any[]} args error messages
29
- * @returns {void}
30
- */
31
- e: LoggerFunc;
32
- /**
33
- * @description Method used to print warn logs
34
- * @method
35
- *
36
- * @example
37
- * logger.w("warn message") // warn message
38
- *
39
- * @param {...any[]} args warn messages
40
- * @returns {void}
41
- */
42
- w: LoggerFunc;
43
- /**
44
- * @description Method used to print info logs
45
- * @method
46
- *
47
- * @example
48
- * logger.i("info message") // info message
49
- *
50
- * @param {...any[]} args info messages
51
- * @returns {void}
52
- */
53
- i: LoggerFunc;
54
- /**
55
- * @description Method used to print verbose logs
56
- * @method
57
- *
58
- * @example
59
- * logger.v("verbose message") // verbose message
60
- *
61
- * @param {...any[]} args verbose messages
62
- * @returns {void}
63
- */
64
- v: LoggerFunc;
65
- /**
66
- * @description Method used to print debug logs
67
- * @method
68
- *
69
- * @example
70
- * logger.d("debug message") // debug message
71
- *
72
- * @param {...any[]} msg debug messages
73
- * @returns {void}
74
- */
75
- d: LoggerFunc;
76
- /**
77
- * @description Method used to set logger option and change logger level
78
- *
79
- * @example
80
- * logger.setOptions({level: 'INFO'}) // set logger level
81
- *
82
- * @param {LoggerOptions} options logger options
83
- * @return {void}
84
- */
85
- setOptions(options: Partial<LoggerOptions>): void;
86
- /**
87
- * @description Private method used to match logger level
88
- * @private
89
- *
90
- * @example
91
- * this._matchLevel("DEBUG") // 0
92
- *
93
- * @param {LoggerLevel} level logger level
94
- * @return {number}
95
- */
96
- private _matchLevel;
97
- /**
98
- * @private
99
- * @description Logger factory
100
- * @param {ConsoleKey} type
101
- * @param {boolean} bool
102
- * @returns
103
- */
104
- private _loggerFactory;
105
- /**
106
- * @description Get options
107
- * @returns {LoggerOptions}
108
- */
109
- getOptions(): Partial<LoggerOptions>;
110
- /**
111
- * @description Get version
112
- * @returns {string}
113
- */
114
- version(): string;
115
- }
116
- export default Logger;