@aomex/logger 0.0.23 → 3.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,52 +1,127 @@
1
- # @aomex/logger
1
+ # Change Log
2
2
 
3
- ## 0.0.23
3
+ All notable changes to this project will be documented in this file.
4
+ See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
4
5
 
5
- ### Patch Changes
6
+ # [3.17.0](https://github.com/aomex/aomex/compare/v3.16.0...v3.17.0) (2025-03-09)
6
7
 
7
- - [`8becf8e`](https://github.com/aomex/aomex/commit/8becf8ee5ef86a5909783d0654e536db7be9bf5b) Thanks [@geekact](https://github.com/geekact)! - refactor(core): 工具移动到新的包@aomex/internal-tools
8
8
 
9
- - Updated dependencies [[`00bafbb`](https://github.com/aomex/aomex/commit/00bafbbac2d32205b63a6bf561fb0a69c38a54bb), [`8becf8e`](https://github.com/aomex/aomex/commit/8becf8ee5ef86a5909783d0654e536db7be9bf5b), [`0776719`](https://github.com/aomex/aomex/commit/077671963401f1dafb5b03722899452d45df13fc), [`f996bf7`](https://github.com/aomex/aomex/commit/f996bf7e529e7751a5e858c579feed33f5f02d65)]:
10
- - @aomex/core@0.0.27
11
- - @aomex/web@0.0.28
12
- - @aomex/internal-tools@0.0.27
9
+ ### Features
13
10
 
14
- ## 0.0.22
11
+ * **logger:** 增加方法countTransports ([3bb0a90](https://github.com/aomex/aomex/commit/3bb0a904a79d2699d6b4b8970f9e99a65c571426))
12
+ * **logger:** 独立安装 ([9a3f444](https://github.com/aomex/aomex/commit/9a3f4446ba7dd2da9a7f52eec8891624e9208435))
15
13
 
16
- ### Patch Changes
17
14
 
18
- - Updated dependencies [[`33c3c61`](https://github.com/aomex/aomex/commit/33c3c614be9f66077f7487350b88d2db854f5fc8), [`fbcea3d`](https://github.com/aomex/aomex/commit/fbcea3d68ff033e6861130c645c8e5ad7336193f)]:
19
- - @aomex/web@0.0.27
20
- - @aomex/core@0.0.26
21
15
 
22
- ## 0.0.21
23
16
 
24
- ### Patch Changes
25
17
 
26
- - Updated dependencies [[`5ef2022`](https://github.com/aomex/aomex/commit/5ef202248b4320ff9076fbecb54379055cffb7db), [`8d9e9d8`](https://github.com/aomex/aomex/commit/8d9e9d8ece0bbcc7e1ac685702eacbfdfa145aa9), [`0e6ed2c`](https://github.com/aomex/aomex/commit/0e6ed2c611100dcfaafb6fb41357624ad9f5c67a)]:
27
- - @aomex/web@0.0.26
28
- - @aomex/core@0.0.25
18
+ # [3.16.0](https://github.com/aomex/aomex/compare/v3.15.1...v3.16.0) (2025-03-09)
29
19
 
30
- ## 0.0.20
31
20
 
32
- ### Patch Changes
21
+ ### Features
33
22
 
34
- - Updated dependencies [[`2ac62fd`](https://github.com/aomex/aomex/commit/2ac62fd28166a1d9dd60b3c6d5a6508a6f9ee82b), [`4258410`](https://github.com/aomex/aomex/commit/42584107ad9f7e34492ae1053fef83aa2d9d747a), [`4177cba`](https://github.com/aomex/aomex/commit/4177cba7877e38120842bd8d287eaed54e4926ca)]:
35
- - @aomex/core@0.0.24
36
- - @aomex/web@0.0.25
23
+ * **logger:** 使用新的文件名日期占位符 ([3bde946](https://github.com/aomex/aomex/commit/3bde9464bf9485238024462842108bd6af267af2))
24
+ * **logger:** 增加通用类CustomTransport ([d8254c3](https://github.com/aomex/aomex/commit/d8254c382b3daf924e98856cccc416ce9c0ce316))
37
25
 
38
- ## 0.0.19
39
26
 
40
- ### Patch Changes
41
27
 
42
- - Updated dependencies [[`6621e4f`](https://github.com/aomex/aomex/commit/6621e4ff0f3509beeb332a0571a7db9c7d6ca99a), [`7b09277`](https://github.com/aomex/aomex/commit/7b09277136910966f500c8132303c7ddee84340c), [`46c5b72`](https://github.com/aomex/aomex/commit/46c5b72785011fa181767f4c8ea0d0f5008b21ae), [`9c78999`](https://github.com/aomex/aomex/commit/9c78999ebcb2962f30344acfbf6de0733d6fdd41), [`f4b012d`](https://github.com/aomex/aomex/commit/f4b012d98cddb2918479ea05df6c266dd914e53a)]:
43
- - @aomex/web@0.0.24
44
- - @aomex/core@0.0.23
45
28
 
46
- ## 0.0.18
47
29
 
48
- ### Patch Changes
30
+ ## [3.15.1](https://github.com/aomex/aomex/compare/v3.15.0...v3.15.1) (2025-02-09)
49
31
 
50
- - Updated dependencies [[`6f7d706`](https://github.com/aomex/aomex/commit/6f7d7066c23711abdd149eb1c9a293ab8c4284a4), [`e21007a`](https://github.com/aomex/aomex/commit/e21007a82cb8eac73e1f696340bbe986d57dc159), [`e7bf93c`](https://github.com/aomex/aomex/commit/e7bf93cee6896c61d0bf3eb0921151dc6c1bc107), [`e21007a`](https://github.com/aomex/aomex/commit/e21007a82cb8eac73e1f696340bbe986d57dc159), [`818e840`](https://github.com/aomex/aomex/commit/818e840d36c7456a863fc071968b246c123c17f5), [`fb6c72d`](https://github.com/aomex/aomex/commit/fb6c72dbb266be4db92a542afe93dfa5d8c7cd41)]:
51
- - @aomex/core@0.0.22
52
- - @aomex/web@0.0.23
32
+ **Note:** Version bump only for package @aomex/common-logger
33
+
34
+
35
+
36
+
37
+
38
+ # [3.15.0](https://github.com/aomex/aomex/compare/v3.14.2...v3.15.0) (2025-02-09)
39
+
40
+ **Note:** Version bump only for package @aomex/common-logger
41
+
42
+
43
+
44
+
45
+
46
+ ## [3.14.2](https://github.com/aomex/aomex/compare/v3.14.1...v3.14.2) (2025-01-14)
47
+
48
+ **Note:** Version bump only for package @aomex/common-logger
49
+
50
+
51
+
52
+
53
+
54
+ ## [3.14.1](https://github.com/aomex/aomex/compare/v3.14.0...v3.14.1) (2025-01-09)
55
+
56
+ **Note:** Version bump only for package @aomex/common-logger
57
+
58
+
59
+
60
+
61
+
62
+ # [3.14.0](https://github.com/aomex/aomex/compare/v3.13.1...v3.14.0) (2025-01-02)
63
+
64
+ **Note:** Version bump only for package @aomex/common-logger
65
+
66
+
67
+
68
+
69
+
70
+ ## [3.13.1](https://github.com/aomex/aomex/compare/v3.13.0...v3.13.1) (2024-12-29)
71
+
72
+ **Note:** Version bump only for package @aomex/common-logger
73
+
74
+
75
+
76
+
77
+
78
+ # [3.13.0](https://github.com/aomex/aomex/compare/v3.12.1...v3.13.0) (2024-12-27)
79
+
80
+ **Note:** Version bump only for package @aomex/common-logger
81
+
82
+
83
+
84
+
85
+
86
+ ## [3.12.1](https://github.com/aomex/aomex/compare/v3.12.0...v3.12.1) (2024-12-19)
87
+
88
+ **Note:** Version bump only for package @aomex/common-logger
89
+
90
+
91
+
92
+
93
+
94
+ # [3.12.0](https://github.com/aomex/aomex/compare/v3.11.0...v3.12.0) (2024-11-07)
95
+
96
+ **Note:** Version bump only for package @aomex/common-logger
97
+
98
+
99
+
100
+
101
+
102
+ # [3.11.0](https://github.com/aomex/aomex/compare/v3.10.0...v3.11.0) (2024-11-07)
103
+
104
+ **Note:** Version bump only for package @aomex/common-logger
105
+
106
+
107
+
108
+
109
+
110
+ # [3.10.0](https://github.com/aomex/aomex/compare/v3.9.0...v3.10.0) (2024-11-02)
111
+
112
+
113
+ ### Features
114
+
115
+ * **logger:** timestamp使用日期类型 ([26a5931](https://github.com/aomex/aomex/commit/26a5931ca0a9dfdb5a7abcdfd967092e5334aa04))
116
+ * **logger:** 增加promise方法以保证日志输送完毕 ([1945be3](https://github.com/aomex/aomex/commit/1945be387d142c71bdc79faabe1216f4c072642e))
117
+
118
+
119
+
120
+
121
+
122
+ # [3.9.0](https://github.com/aomex/aomex/compare/v3.8.1...v3.9.0) (2024-10-30)
123
+
124
+
125
+ ### Features
126
+
127
+ * **common:** 增加日志系统 ([99c93b3](https://github.com/aomex/aomex/commit/99c93b3f2eadd7cd1749ed53450c64a66d309e4b))
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2023 geekact
3
+ Copyright (c) 2023-2024 geekact
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/dist/index.d.ts CHANGED
@@ -1,32 +1,166 @@
1
- import { WebContext, WebMiddleware } from '@aomex/web';
1
+ import { styleText } from 'node:util';
2
+ import tty from 'node:tty';
3
+ import { Mode } from 'node:fs';
2
4
 
3
- type Printer = (message: string, ...args: any[]) => any;
4
- interface LoggerOptions {
5
+ declare abstract class LoggerTransport {
6
+ abstract consume(log: Logger.Log): Promise<any>;
5
7
  /**
6
- * Defaults ` [request] [ip] [method] [url]`
8
+ * 解析日期。返回 年、月、日、时、分、秒
7
9
  */
8
- requestFormat?: string | false;
10
+ protected dateToJSON(date: Date): {
11
+ year: string;
12
+ month: string;
13
+ day: string;
14
+ hour: string;
15
+ minute: string;
16
+ second: string;
17
+ };
9
18
  /**
10
- * Defaults ` [response] [ip] [method] [url] [statusCode] [time] [contentLength]`
19
+ * 时间字符串:`年-月-日 时:分:秒`
11
20
  */
12
- responseFormat?: string | false;
13
- printer?: Printer;
14
- customTokens?: {
15
- [key: string]: (ctx: WebContext) => string;
21
+ protected dateToString(date: Date): string;
22
+ protected prettifyError(error: string | Error, opts?: {
23
+ /**
24
+ * 删除错误栈包含node:internal路径的文件。默认:`true`
25
+ */
26
+ removeNodeInternal?: boolean;
27
+ /**
28
+ * 删除错误栈包含node_module路径的文件。默认:`true`
29
+ */
30
+ removeNodeModule?: boolean;
31
+ /**
32
+ * 错误栈完整路径转化为相对路径。默认:`true`
33
+ */
34
+ toRelativePath?: boolean;
35
+ /**
36
+ * 删除错误栈前缀` at`。默认:`false`
37
+ */
38
+ removeAt?: boolean;
39
+ }): {
40
+ message: string;
41
+ stack: string;
16
42
  };
17
43
  }
18
- declare const logger: (options?: LoggerOptions) => WebMiddleware;
19
44
 
20
- declare enum FormatToken {
21
- request = "[request]",
22
- response = "[response]",
23
- method = "[method]",
24
- url = "[url]",
25
- statusCode = "[statusCode]",
26
- contentLength = "[contentLength]",
27
- contentType = "[contentType]",
28
- time = "[time]",
29
- ip = "[ip]"
45
+ declare class CustomTransport extends LoggerTransport {
46
+ protected readonly consumeHandle: (this: LoggerTransport, log: Logger.Log) => Promise<any>;
47
+ constructor(opts: {
48
+ consume: (this: LoggerTransport, log: Logger.Log) => Promise<any>;
49
+ });
50
+ consume(log: Logger.Log): Promise<any>;
51
+ }
52
+
53
+ declare class ConsoleTransport extends LoggerTransport {
54
+ protected readonly colors: Record<string, Parameters<typeof styleText>[0]>;
55
+ protected readonly writer: tty.WriteStream;
56
+ constructor(opts?: {
57
+ colors?: Record<string, Parameters<typeof styleText>[0]>;
58
+ output?: tty.WriteStream;
59
+ });
60
+ consume(log: Logger.Log): Promise<any>;
61
+ }
62
+
63
+ declare class FileTransport extends LoggerTransport {
64
+ protected readonly file: string | ((log: Logger.Log) => string);
65
+ protected readonly fileMode?: Mode;
66
+ protected readonly dirMode?: Mode;
67
+ constructor(opts: {
68
+ /**
69
+ * 日志文件路径,支持引入时间占位符。
70
+ * - `{year}` 年
71
+ * - `{month}` 月
72
+ * - `{day}` 日
73
+ * - `{hour}` 时
74
+ * - `{minute}` 分
75
+ * - `{second}` 秒
76
+ *
77
+ * ```typescript
78
+ * new FileTransport({
79
+ * file: `./logs/{year}-{month}-{day}/{hour}.log`,
80
+ * })
81
+ * ```
82
+ */
83
+ file: string | ((log: Logger.Log) => string);
84
+ /**
85
+ * 文件权限,默认使用系统权限
86
+ */
87
+ fileMode?: Mode;
88
+ /**
89
+ * 文件夹权限,默认使用系统权限
90
+ */
91
+ dirMode?: Mode;
92
+ });
93
+ consume(log: Logger.Log): Promise<any>;
94
+ protected getContent(message: Logger.Log): string;
95
+ }
96
+
97
+ declare namespace Logger {
98
+ type Level<T extends string> = 'all' | 'none' | T[] | {
99
+ from: T;
100
+ to?: T;
101
+ } | {
102
+ from?: T;
103
+ to: T;
104
+ } | {
105
+ from: T;
106
+ to: T;
107
+ };
108
+ interface Options<T extends string> {
109
+ levels: T[];
110
+ transports?: {
111
+ /**
112
+ * 接收日志。内置方案汇聚在 `Logger.transports` 属性中。用户也可以自己实现
113
+ */
114
+ transport: LoggerTransport;
115
+ /**
116
+ * 日志输出等级,有以下几种传值方式:
117
+ * - `all` 输出全部等级的日志
118
+ * - `none` 关闭日志输出
119
+ * - `[ ]` 输出指定的等级的日志,空数组则代表关闭日志输出
120
+ * - `{ min?, max? }` 输出等级区间内的日志,min的分数必须<=max的分数,否则关闭日志输出
121
+ */
122
+ level: Level<NoInfer<T>>;
123
+ }[];
124
+ }
125
+ interface Log<T extends string = string> {
126
+ timestamp: Date;
127
+ level: T;
128
+ text: string;
129
+ }
130
+ }
131
+ declare abstract class Logger<T extends string> {
132
+ static transports: {
133
+ readonly File: typeof FileTransport;
134
+ readonly Console: typeof ConsoleTransport;
135
+ readonly Custom: typeof CustomTransport;
136
+ };
137
+ static create: <T extends string>(opts: Logger.Options<T_1>) => Logger<T_1> & { [K in T_1]: (text: string, ...args: any[]) => void; };
138
+ protected readonly levels: T[];
139
+ protected readonly logs: Logger.Log<T>[];
140
+ protected transportAndLevels: {
141
+ transport: LoggerTransport;
142
+ levels: T[];
143
+ }[];
144
+ protected timer?: NodeJS.Timeout;
145
+ readonly transports: {
146
+ add(opts: {
147
+ transport: LoggerTransport;
148
+ level: Logger.Level<T>;
149
+ }): void;
150
+ remove(strip: (transport: LoggerTransport, levels: T[]) => boolean): void;
151
+ };
152
+ constructor(opts: Logger.Options<T>);
153
+ /**
154
+ * 保证日志(异步)输送完毕
155
+ */
156
+ complete(): Promise<void>;
157
+ /**
158
+ * 统计某个级别有几个消费实例
159
+ */
160
+ countTransports(level: T): number;
161
+ protected log(level: T, text: string, ...args: any[]): void;
162
+ protected consume(): Promise<void>;
163
+ protected transformLevel(level: Logger.Level<T>): T[];
30
164
  }
31
165
 
32
- export { FormatToken, LoggerOptions, logger };
166
+ export { Logger, LoggerTransport };
package/dist/index.js CHANGED
@@ -1,190 +1,228 @@
1
- // src/logger.ts
2
- import { Readable } from "node:stream";
3
- import util from "node:util";
4
- import { middleware } from "@aomex/core";
5
-
6
- // src/counter.ts
7
- import { Transform } from "node:stream";
8
- var Counter = class extends Transform {
9
- length = 0;
10
- _transform(chunk, _encoding, callback) {
11
- this.length += chunk.length;
12
- this.push(chunk);
13
- callback();
1
+ // src/logger-transport.ts
2
+ import path from "node:path";
3
+ var LoggerTransport = class {
4
+ /**
5
+ * 解析日期。返回 年、月、日、时、分、秒
6
+ */
7
+ dateToJSON(date) {
8
+ return {
9
+ year: date.getFullYear().toString(),
10
+ month: (date.getMonth() + 1).toString().padStart(2, "0"),
11
+ day: date.getDate().toString().padStart(2, "0"),
12
+ hour: date.getHours().toString().padStart(2, "0"),
13
+ minute: date.getMinutes().toString().padStart(2, "0"),
14
+ second: date.getSeconds().toString().padStart(2, "0")
15
+ };
16
+ }
17
+ /**
18
+ * 时间字符串:`年-月-日 时:分:秒`
19
+ */
20
+ dateToString(date) {
21
+ const parsed = this.dateToJSON(date);
22
+ return `${parsed.year}-${parsed.month}-${parsed.day} ${parsed.hour}:${parsed.minute}:${parsed.second}`;
23
+ }
24
+ prettifyError(error, opts = {}) {
25
+ const {
26
+ removeNodeModule = true,
27
+ removeNodeInternal = true,
28
+ removeAt = false,
29
+ toRelativePath = true
30
+ } = opts;
31
+ const cwd = process.cwd();
32
+ const errorMsgAndStacks = (typeof error === "string" ? error : error.stack || "").split("\n");
33
+ const stackIndex = Math.max(
34
+ 1,
35
+ errorMsgAndStacks.findIndex((item) => /^\s+at\s+/.test(item))
36
+ );
37
+ const message = errorMsgAndStacks.slice(0, stackIndex).join("\n");
38
+ const stack = errorMsgAndStacks.slice(stackIndex).filter((item) => {
39
+ return (!removeNodeInternal || !item.includes("node:internal")) && (!removeNodeModule || !item.includes("node_modules/"));
40
+ }).map((item) => {
41
+ if (toRelativePath) {
42
+ item = item.replaceAll("file://", "").replaceAll(cwd + path.sep, "");
43
+ }
44
+ if (removeAt) {
45
+ item = item.replaceAll(/^\s+at\s+(?:async\s+)?/gi, " ".repeat(4));
46
+ }
47
+ return item;
48
+ }).join("\n");
49
+ return { message, stack };
14
50
  }
15
51
  };
16
52
 
17
- // src/format.ts
18
- import prettyTime from "pretty-time";
19
- import { bytes, chalk } from "@aomex/internal-tools";
20
- import { statuses } from "@aomex/web";
21
-
22
- // src/format-token.ts
23
- var FormatToken = /* @__PURE__ */ ((FormatToken2) => {
24
- FormatToken2["request"] = "[request]";
25
- FormatToken2["response"] = "[response]";
26
- FormatToken2["method"] = "[method]";
27
- FormatToken2["url"] = "[url]";
28
- FormatToken2["statusCode"] = "[statusCode]";
29
- FormatToken2["contentLength"] = "[contentLength]";
30
- FormatToken2["contentType"] = "[contentType]";
31
- FormatToken2["time"] = "[time]";
32
- FormatToken2["ip"] = "[ip]";
33
- return FormatToken2;
34
- })(FormatToken || {});
53
+ // src/transports/custom-transport.ts
54
+ var CustomTransport = class extends LoggerTransport {
55
+ consumeHandle;
56
+ constructor(opts) {
57
+ super();
58
+ this.consumeHandle = opts.consume.bind(this);
59
+ }
60
+ async consume(log) {
61
+ return this.consumeHandle(log);
62
+ }
63
+ };
35
64
 
36
- // src/format.ts
37
- var colorCodes = {
38
- 7: "magenta",
39
- 5: "red",
40
- 4: "yellow",
41
- 3: "cyan",
42
- 2: "green",
43
- 1: "green",
44
- 0: "yellow"
65
+ // src/transports/console-transport.ts
66
+ import { styleText } from "node:util";
67
+ var ConsoleTransport = class extends LoggerTransport {
68
+ colors;
69
+ writer;
70
+ constructor(opts = {}) {
71
+ super();
72
+ this.colors = opts.colors || {};
73
+ this.writer = opts.output || process.stdout;
74
+ }
75
+ async consume(log) {
76
+ const color = this.colors[log.level];
77
+ const time = this.dateToString(log.timestamp);
78
+ const level = `[${log.level}]`;
79
+ this.writer.write(
80
+ `${color ? styleText(color, level) : level} ${color ? styleText(color, time) : time} ${log.text}
81
+ `
82
+ );
83
+ }
45
84
  };
46
- var format = (opts) => {
47
- const {
48
- message,
49
- startTime,
50
- request,
51
- response = {},
52
- tokens = {},
53
- finished
54
- } = opts;
55
- const { method, url } = request;
56
- const { contentLength, contentType = "-", statusCode = 404 } = response;
57
- const args = [];
58
- const formatted = message.replaceAll(/\[[^\]]+\]/g, (token) => {
59
- token = token.slice(1, -1);
60
- if (tokens[token]) {
61
- args.push(tokens[token]());
62
- return "%s";
63
- }
64
- switch (`[${token}]`) {
65
- case "[request]" /* request */:
66
- args.push("<--");
67
- return chalk.gray("%s");
68
- case "[response]" /* response */:
69
- if (statusCode >= 400) {
70
- args.push("xxx");
71
- return chalk.red("%s");
72
- }
73
- if (finished === false) {
74
- args.push("-x-");
75
- return chalk.yellow("%s");
76
- }
77
- args.push("-->");
78
- return chalk.gray("%s");
79
- case "[method]" /* method */:
80
- args.push(method);
81
- return chalk.bold("%s");
82
- case "[url]" /* url */:
83
- args.push(url);
84
- return chalk.gray("%s");
85
- case "[statusCode]" /* statusCode */:
86
- const c = colorCodes[statusCode / 100 | 0] || colorCodes[0];
87
- args.push(statusCode.toString());
88
- return chalk[c]("%s");
89
- case "[contentLength]" /* contentLength */:
90
- args.push(
91
- statuses.empty[statusCode] || contentLength === 0 ? "0" : contentLength == null ? "-" : bytes(contentLength).toLowerCase()
92
- );
93
- return chalk.gray("%s");
94
- case "[contentType]" /* contentType */:
95
- args.push(contentType);
96
- return chalk.gray("%s");
97
- case "[time]" /* time */:
98
- args.push(prettyTime(process.hrtime(startTime)));
99
- return chalk.gray("%s");
100
- case "[ip]" /* ip */:
101
- args.push(request.ip);
102
- return chalk.gray("%s");
103
- default:
104
- return `[${token}]`;
85
+
86
+ // src/transports/file-transport.ts
87
+ import { dirname } from "node:path";
88
+ import { stripVTControlCharacters } from "node:util";
89
+ import { appendFile, mkdir } from "node:fs/promises";
90
+ var FileTransport = class extends LoggerTransport {
91
+ file;
92
+ fileMode;
93
+ dirMode;
94
+ constructor(opts) {
95
+ super();
96
+ this.file = opts.file;
97
+ this.fileMode = opts.fileMode;
98
+ this.dirMode = opts.dirMode;
99
+ }
100
+ async consume(log) {
101
+ let file;
102
+ if (typeof this.file === "function") {
103
+ file = this.file(log);
104
+ } else {
105
+ file = this.file;
106
+ for (const [key, value] of Object.entries(this.dateToJSON(log.timestamp))) {
107
+ file = file.replaceAll(`{${key}}`, value);
108
+ }
105
109
  }
106
- });
107
- return [formatted, ...args];
110
+ await mkdir(dirname(file), { recursive: true, mode: this.dirMode });
111
+ await appendFile(file, this.getContent(log), { mode: this.fileMode });
112
+ }
113
+ getContent(message) {
114
+ return `
115
+ [${message.level}] ${this.dateToString(message.timestamp)} ${stripVTControlCharacters(message.text)}
116
+ `;
117
+ }
108
118
  };
109
119
 
110
- // src/logger.ts
111
- var defaultPrinter = (message, ...args) => {
112
- console.log(util.format(message, ...args));
120
+ // src/transports/index.ts
121
+ var transports = {
122
+ File: FileTransport,
123
+ Console: ConsoleTransport,
124
+ Custom: CustomTransport
113
125
  };
114
- var defaultRequestFormat = ` ${"[request]" /* request */} ${"[ip]" /* ip */} ${"[method]" /* method */} ${"[url]" /* url */}`;
115
- var defaultResponseFormat = ` ${"[response]" /* response */} ${"[ip]" /* ip */} ${"[method]" /* method */} ${"[url]" /* url */} ${"[statusCode]" /* statusCode */} ${"[time]" /* time */} ${"[contentLength]" /* contentLength */}`;
116
- var logger = (options = {}) => {
117
- const {
118
- requestFormat = defaultRequestFormat,
119
- responseFormat = defaultResponseFormat,
120
- printer = defaultPrinter,
121
- customTokens
122
- } = options;
123
- return middleware.web(async (ctx, next) => {
124
- const start = process.hrtime();
125
- const { request, response } = ctx;
126
- const tokens = customTokens ? Object.fromEntries(
127
- Object.entries(customTokens).map(([key, value]) => {
128
- return [key, value.bind(null, ctx)];
129
- })
130
- ) : {};
131
- if (requestFormat) {
132
- printer(
133
- ...format({
134
- message: requestFormat,
135
- tokens,
136
- startTime: start,
137
- request
138
- })
139
- );
126
+
127
+ // src/logger.ts
128
+ import util from "node:util";
129
+ import timers from "node:timers/promises";
130
+ var Logger = class _Logger {
131
+ static transports = transports;
132
+ static create = (opts) => {
133
+ return new _Logger(opts);
134
+ };
135
+ levels;
136
+ logs = [];
137
+ transportAndLevels;
138
+ timer;
139
+ transports;
140
+ constructor(opts) {
141
+ this.levels = opts.levels;
142
+ this.transportAndLevels = (opts.transports || []).map(({ transport, level }) => {
143
+ return {
144
+ transport,
145
+ levels: this.transformLevel(level)
146
+ };
147
+ });
148
+ this.levels.forEach((level) => {
149
+ Object.defineProperty(this, level, {
150
+ value: this.log.bind(this, level)
151
+ });
152
+ });
153
+ this.transports = {
154
+ add: (opts2) => {
155
+ this.transportAndLevels.push({
156
+ transport: opts2.transport,
157
+ levels: this.transformLevel(opts2.level)
158
+ });
159
+ },
160
+ remove: (strip) => {
161
+ this.transportAndLevels = this.transportAndLevels.filter(
162
+ ({ transport, levels }) => {
163
+ return !strip(transport, levels);
164
+ }
165
+ );
166
+ }
167
+ };
168
+ }
169
+ /**
170
+ * 保证日志(异步)输送完毕
171
+ */
172
+ async complete() {
173
+ while (true) {
174
+ if (!this.timer) return;
175
+ if (!this.logs.length) return;
176
+ await timers.setTimeout(50);
140
177
  }
141
- if (!responseFormat)
142
- return next();
143
- ctx.app.on("error", onError);
144
- await next();
145
- ctx.app.off("error", onError);
146
- const body = response.body;
147
- let counter;
148
- if (body instanceof Readable && body.readable) {
149
- ctx.send(body.pipe(counter = new Counter()));
178
+ }
179
+ /**
180
+ * 统计某个级别有几个消费实例
181
+ */
182
+ countTransports(level) {
183
+ let counter = 0;
184
+ for (const { levels } of this.transportAndLevels) {
185
+ if (levels.includes(level)) ++counter;
150
186
  }
151
- const onfinish = onDone.bind(null, "finish");
152
- const onclose = onDone.bind(null, "close");
153
- response.once("finish", onfinish);
154
- response.once("close", onclose);
155
- function onError() {
156
- printer(
157
- ...format({
158
- message: responseFormat,
159
- tokens,
160
- startTime: start,
161
- request,
162
- response
187
+ return counter;
188
+ }
189
+ log(level, text, ...args) {
190
+ this.logs.push({
191
+ timestamp: /* @__PURE__ */ new Date(),
192
+ text: util.format(text, ...args),
193
+ level
194
+ });
195
+ this.timer ||= setTimeout(async () => {
196
+ await this.consume();
197
+ this.timer = void 0;
198
+ });
199
+ }
200
+ async consume() {
201
+ let log = this.logs.shift();
202
+ while (log) {
203
+ const targetLevel = log.level;
204
+ await Promise.all(
205
+ this.transportAndLevels.map(async ({ transport, levels }) => {
206
+ if (levels.includes(targetLevel)) {
207
+ await transport.consume(log);
208
+ }
163
209
  })
164
210
  );
211
+ log = this.logs.shift();
165
212
  }
166
- function onDone(event) {
167
- response.off("finish", onfinish);
168
- response.off("close", onclose);
169
- printer(
170
- ...format({
171
- message: responseFormat,
172
- tokens,
173
- startTime: start,
174
- request,
175
- response: {
176
- statusCode: response.statusCode,
177
- contentType: response.contentType,
178
- contentLength: counter ? counter.length : response.contentLength
179
- },
180
- finished: event === "finish"
181
- })
182
- );
213
+ }
214
+ transformLevel(level) {
215
+ if (typeof level !== "object") {
216
+ return level === "all" ? [...this.levels] : [];
183
217
  }
184
- });
218
+ if (Array.isArray(level)) return [...new Set(level)];
219
+ const min = level.from ? this.levels.findIndex((l) => l === level.from) : 0;
220
+ const max = level.to ? this.levels.findIndex((l) => l === level.to) + 1 : this.levels.length;
221
+ return this.levels.slice(min, max);
222
+ }
185
223
  };
186
224
  export {
187
- FormatToken,
188
- logger
225
+ Logger,
226
+ LoggerTransport
189
227
  };
190
228
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/logger.ts","../src/counter.ts","../src/format.ts","../src/format-token.ts"],"sourcesContent":["import { Readable } from 'node:stream';\nimport util from 'node:util';\nimport { middleware } from '@aomex/core';\nimport type { WebContext, WebMiddleware } from '@aomex/web';\nimport { Counter } from './counter';\nimport { format } from './format';\nimport { FormatToken } from './format-token';\n\ntype Printer = (message: string, ...args: any[]) => any;\n\nexport interface LoggerOptions {\n /**\n * Defaults ` [request] [ip] [method] [url]`\n */\n requestFormat?: string | false;\n /**\n * Defaults ` [response] [ip] [method] [url] [statusCode] [time] [contentLength]`\n */\n responseFormat?: string | false;\n printer?: Printer;\n customTokens?: { [key: string]: (ctx: WebContext) => string };\n}\n\nconst defaultPrinter: Printer = (message, ...args) => {\n console.log(util.format(message, ...args));\n};\n\nconst defaultRequestFormat = ` ${FormatToken.request} ${FormatToken.ip} ${FormatToken.method} ${FormatToken.url}`;\nconst defaultResponseFormat = ` ${FormatToken.response} ${FormatToken.ip} ${FormatToken.method} ${FormatToken.url} ${FormatToken.statusCode} ${FormatToken.time} ${FormatToken.contentLength}`;\n\nexport const logger = (options: LoggerOptions = {}): WebMiddleware => {\n const {\n requestFormat = defaultRequestFormat,\n responseFormat = defaultResponseFormat,\n printer = defaultPrinter,\n customTokens,\n } = options;\n\n return middleware.web(async (ctx, next) => {\n const start = process.hrtime();\n const { request, response } = ctx;\n const tokens = customTokens\n ? Object.fromEntries(\n Object.entries(customTokens).map(([key, value]) => {\n return [key, value.bind(null, ctx)];\n }),\n )\n : {};\n\n if (requestFormat) {\n printer(\n ...format({\n message: requestFormat!,\n tokens,\n startTime: start,\n request,\n }),\n );\n }\n\n if (!responseFormat) return next();\n\n ctx.app.on('error', onError);\n await next();\n ctx.app.off('error', onError);\n\n const body = response.body;\n let counter: Counter;\n\n if (body instanceof Readable && body.readable) {\n ctx.send(body.pipe((counter = new Counter())));\n }\n\n const onfinish = onDone.bind(null, 'finish');\n const onclose = onDone.bind(null, 'close');\n response.once('finish', onfinish);\n response.once('close', onclose);\n\n function onError() {\n printer(\n ...format({\n message: responseFormat as string,\n tokens,\n startTime: start,\n request,\n response,\n }),\n );\n }\n\n function onDone(event: 'finish' | 'close') {\n response.off('finish', onfinish);\n response.off('close', onclose);\n printer(\n ...format({\n message: responseFormat as string,\n tokens,\n startTime: start,\n request,\n response: {\n statusCode: response.statusCode,\n contentType: response.contentType,\n contentLength: counter ? counter.length : response.contentLength,\n },\n finished: event === 'finish',\n }),\n );\n }\n });\n};\n","import { Transform, type TransformCallback } from 'node:stream';\n\nexport class Counter extends Transform {\n public length: number = 0;\n\n override _transform(\n chunk: any,\n _encoding: BufferEncoding,\n callback: TransformCallback,\n ): void {\n this.length += chunk.length;\n this.push(chunk);\n callback();\n }\n}\n","import prettyTime from 'pretty-time';\nimport { bytes, chalk } from '@aomex/internal-tools';\nimport { statuses } from '@aomex/web';\nimport { FormatToken } from './format-token';\n\nexport const colorCodes = <const>{\n 7: 'magenta',\n 5: 'red',\n 4: 'yellow',\n 3: 'cyan',\n 2: 'green',\n 1: 'green',\n 0: 'yellow',\n};\n\nexport const format = (opts: {\n message: string;\n startTime: [number, number];\n tokens?: { [key: string]: () => string };\n finished?: boolean;\n request: {\n method: string;\n url: string;\n ip: string;\n };\n response?: {\n statusCode?: number;\n contentType?: string;\n contentLength?: number;\n };\n}): [message: string, ...args: any[]] => {\n const {\n message,\n startTime,\n request,\n response = {},\n tokens = {},\n finished,\n } = opts;\n const { method, url } = request;\n const { contentLength, contentType = '-', statusCode = 404 } = response;\n\n const args: string[] = [];\n const formatted = message.replaceAll(/\\[[^\\]]+\\]/g, (token) => {\n token = token.slice(1, -1);\n\n if (tokens[token]) {\n args.push(tokens[token]!());\n return '%s';\n }\n\n switch (`[${token}]`) {\n case FormatToken.request:\n args.push('<--');\n return chalk.gray('%s');\n case FormatToken.response:\n if (statusCode >= 400) {\n args.push('xxx');\n return chalk.red('%s');\n }\n if (finished === false) {\n args.push('-x-');\n return chalk.yellow('%s');\n }\n\n args.push('-->');\n return chalk.gray('%s');\n case FormatToken.method:\n args.push(method);\n return chalk.bold('%s');\n case FormatToken.url:\n args.push(url);\n return chalk.gray('%s');\n case FormatToken.statusCode:\n const c =\n colorCodes[((statusCode / 100) | 0) as keyof typeof colorCodes] ||\n colorCodes[0]!;\n args.push(statusCode.toString());\n return chalk[c]('%s');\n case FormatToken.contentLength:\n args.push(\n statuses.empty[statusCode] || contentLength === 0\n ? '0'\n : contentLength == null\n ? '-'\n : bytes(contentLength).toLowerCase(),\n );\n return chalk.gray('%s');\n case FormatToken.contentType:\n args.push(contentType);\n return chalk.gray('%s');\n case FormatToken.time:\n args.push(prettyTime(process.hrtime(startTime)));\n return chalk.gray('%s');\n case FormatToken.ip:\n args.push(request.ip);\n return chalk.gray('%s');\n default:\n return `[${token}]`;\n }\n });\n\n return [formatted, ...args];\n};\n","export enum FormatToken {\n request = '[request]',\n response = '[response]',\n method = '[method]',\n url = '[url]',\n statusCode = '[statusCode]',\n contentLength = '[contentLength]',\n contentType = '[contentType]',\n time = '[time]',\n ip = '[ip]',\n}\n"],"mappings":";AAAA,SAAS,gBAAgB;AACzB,OAAO,UAAU;AACjB,SAAS,kBAAkB;;;ACF3B,SAAS,iBAAyC;AAE3C,IAAM,UAAN,cAAsB,UAAU;AAAA,EAC9B,SAAiB;AAAA,EAEf,WACP,OACA,WACA,UACM;AACN,SAAK,UAAU,MAAM;AACrB,SAAK,KAAK,KAAK;AACf,aAAS;AAAA,EACX;AACF;;;ACdA,OAAO,gBAAgB;AACvB,SAAS,OAAO,aAAa;AAC7B,SAAS,gBAAgB;;;ACFlB,IAAK,cAAL,kBAAKA,iBAAL;AACL,EAAAA,aAAA,aAAU;AACV,EAAAA,aAAA,cAAW;AACX,EAAAA,aAAA,YAAS;AACT,EAAAA,aAAA,SAAM;AACN,EAAAA,aAAA,gBAAa;AACb,EAAAA,aAAA,mBAAgB;AAChB,EAAAA,aAAA,iBAAc;AACd,EAAAA,aAAA,UAAO;AACP,EAAAA,aAAA,QAAK;AATK,SAAAA;AAAA,GAAA;;;ADKL,IAAM,aAAoB;AAAA,EAC/B,GAAG;AAAA,EACH,GAAG;AAAA,EACH,GAAG;AAAA,EACH,GAAG;AAAA,EACH,GAAG;AAAA,EACH,GAAG;AAAA,EACH,GAAG;AACL;AAEO,IAAM,SAAS,CAAC,SAekB;AACvC,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA,WAAW,CAAC;AAAA,IACZ,SAAS,CAAC;AAAA,IACV;AAAA,EACF,IAAI;AACJ,QAAM,EAAE,QAAQ,IAAI,IAAI;AACxB,QAAM,EAAE,eAAe,cAAc,KAAK,aAAa,IAAI,IAAI;AAE/D,QAAM,OAAiB,CAA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C3C,UAAM,UAAU,OAAO,KAAK,MAAM,OAAO;AACzC,aAAS,KAAK,UAAU,QAAQ;AAChC,aAAS,KAAK,SAAS,OAAO;AAE9B,aAAS,UAAU;AACjB;AAAA,QACE,GAAG,OAAO;AAAA,UACR,SAAS;AAAA,UACT;AAAA,UACA,WAAW;AAAA,UACX;AAAA,UACA;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF;AAEA,aAAS,OAAO,OAA2B;AACzC,eAAS,IAAI,UAAU,QAAQ;AAC/B,eAAS,IAAI,SAAS,OAAO;AAC7B;AAAA,QACE,GAAG,OAAO;AAAA,UACR,SAAS;AAAA,UACT;AAAA,UACA,WAAW;AAAA,UACX;AAAA,UACA,UAAU;AAAA,YACR,YAAY,SAAS;AAAA,YACrB,aAAa,SAAS;AAAA,YACtB,eAAe,UAAU,QAAQ,SAAS,SAAS;AAAA,UACrD;AAAA,UACA,UAAU,UAAU;AAAA,QACtB,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF,CAAC;AACH;","names":["FormatToken"]}
1
+ {"version":3,"sources":["../src/logger-transport.ts","../src/transports/custom-transport.ts","../src/transports/console-transport.ts","../src/transports/file-transport.ts","../src/transports/index.ts","../src/logger.ts"],"sourcesContent":["import path from 'node:path';\nimport type { Logger } from './logger';\n\nexport abstract class LoggerTransport {\n abstract consume(log: Logger.Log): Promise<any>;\n\n /**\n * 解析日期。返回 年、月、日、时、分、秒\n */\n protected dateToJSON(date: Date) {\n return {\n year: date.getFullYear().toString(),\n month: (date.getMonth() + 1).toString().padStart(2, '0'),\n day: date.getDate().toString().padStart(2, '0'),\n hour: date.getHours().toString().padStart(2, '0'),\n minute: date.getMinutes().toString().padStart(2, '0'),\n second: date.getSeconds().toString().padStart(2, '0'),\n };\n }\n\n /**\n * 时间字符串:`年-月-日 时:分:秒`\n */\n protected dateToString(date: Date) {\n const parsed = this.dateToJSON(date);\n return `${parsed.year}-${parsed.month}-${parsed.day} ${parsed.hour}:${parsed.minute}:${parsed.second}`;\n }\n\n protected prettifyError(\n error: string | Error,\n opts: {\n /**\n * 删除错误栈包含node:internal路径的文件。默认:`true`\n */\n removeNodeInternal?: boolean;\n /**\n * 删除错误栈包含node_module路径的文件。默认:`true`\n */\n removeNodeModule?: boolean;\n /**\n * 错误栈完整路径转化为相对路径。默认:`true`\n */\n toRelativePath?: boolean;\n /**\n * 删除错误栈前缀` at`。默认:`false`\n */\n removeAt?: boolean;\n } = {},\n ) {\n const {\n removeNodeModule = true,\n removeNodeInternal = true,\n removeAt = false,\n toRelativePath = true,\n } = opts;\n const cwd = process.cwd();\n const errorMsgAndStacks = (\n typeof error === 'string' ? error : error.stack || ''\n ).split('\\n');\n const stackIndex = Math.max(\n 1,\n errorMsgAndStacks.findIndex((item) => /^\\s+at\\s+/.test(item)),\n );\n\n const message = errorMsgAndStacks.slice(0, stackIndex).join('\\n');\n const stack = errorMsgAndStacks\n .slice(stackIndex)\n .filter((item) => {\n return (\n (!removeNodeInternal || !item.includes('node:internal')) &&\n (!removeNodeModule || !item.includes('node_modules/'))\n );\n })\n .map((item) => {\n if (toRelativePath) {\n item = item.replaceAll('file://', '').replaceAll(cwd + path.sep, '');\n }\n if (removeAt) {\n item = item.replaceAll(/^\\s+at\\s+(?:async\\s+)?/gi, ' '.repeat(4));\n }\n return item;\n })\n .join('\\n');\n\n return { message, stack };\n }\n}\n","import { LoggerTransport } from '../logger-transport';\nimport type { Logger } from '../logger';\n\nexport class CustomTransport extends LoggerTransport {\n protected readonly consumeHandle: (\n this: LoggerTransport,\n log: Logger.Log,\n ) => Promise<any>;\n\n constructor(opts: {\n consume: (this: LoggerTransport, log: Logger.Log) => Promise<any>;\n }) {\n super();\n this.consumeHandle = opts.consume.bind(this);\n }\n\n override async consume(log: Logger.Log): Promise<any> {\n return this.consumeHandle(log);\n }\n}\n","import { styleText } from 'node:util';\nimport type tty from 'node:tty';\nimport { LoggerTransport } from '../logger-transport';\nimport type { Logger } from '../logger';\n\nexport class ConsoleTransport extends LoggerTransport {\n protected readonly colors: Record<string, Parameters<typeof styleText>[0]>;\n protected readonly writer: tty.WriteStream;\n\n constructor(\n opts: {\n colors?: Record<string, Parameters<typeof styleText>[0]>;\n output?: tty.WriteStream;\n } = {},\n ) {\n super();\n this.colors = opts.colors || {};\n this.writer = opts.output || process.stdout;\n }\n\n override async consume(log: Logger.Log): Promise<any> {\n const color = this.colors[log.level];\n const time = this.dateToString(log.timestamp);\n const level = `[${log.level}]`;\n this.writer.write(\n `${color ? styleText(color, level) : level} ${color ? styleText(color, time) : time} ${log.text}\\n`,\n );\n }\n}\n","import { dirname } from 'node:path';\nimport type { Mode } from 'node:fs';\nimport { stripVTControlCharacters } from 'node:util';\nimport { appendFile, mkdir } from 'node:fs/promises';\nimport { LoggerTransport } from '../logger-transport';\nimport type { Logger } from '../logger';\n\nexport class FileTransport extends LoggerTransport {\n protected readonly file: string | ((log: Logger.Log) => string);\n protected readonly fileMode?: Mode;\n protected readonly dirMode?: Mode;\n\n constructor(opts: {\n /**\n * 日志文件路径,支持引入时间占位符。\n * - `{year}` 年\n * - `{month}` 月\n * - `{day}` 日\n * - `{hour}` 时\n * - `{minute}` 分\n * - `{second}` 秒\n *\n * ```typescript\n * new FileTransport({\n * file: `./logs/{year}-{month}-{day}/{hour}.log`,\n * })\n * ```\n */\n file: string | ((log: Logger.Log) => string);\n /**\n * 文件权限,默认使用系统权限\n */\n fileMode?: Mode;\n /**\n * 文件夹权限,默认使用系统权限\n */\n dirMode?: Mode;\n }) {\n super();\n this.file = opts.file;\n this.fileMode = opts.fileMode;\n this.dirMode = opts.dirMode;\n }\n\n override async consume(log: Logger.Log): Promise<any> {\n let file: string;\n if (typeof this.file === 'function') {\n file = this.file(log);\n } else {\n file = this.file;\n for (const [key, value] of Object.entries(this.dateToJSON(log.timestamp))) {\n file = file.replaceAll(`{${key}}`, value);\n }\n }\n\n await mkdir(dirname(file), { recursive: true, mode: this.dirMode });\n await appendFile(file, this.getContent(log), { mode: this.fileMode });\n }\n\n protected getContent(message: Logger.Log) {\n return `\\n[${message.level}] ${this.dateToString(message.timestamp)} ${stripVTControlCharacters(message.text)}\\n`;\n }\n}\n","import { CustomTransport } from './custom-transport';\nimport { ConsoleTransport } from './console-transport';\nimport { FileTransport } from './file-transport';\n\nexport const transports = <const>{\n File: FileTransport,\n Console: ConsoleTransport,\n Custom: CustomTransport,\n};\n","import type { LoggerTransport } from './logger-transport';\nimport { transports } from './transports';\nimport util from 'node:util';\nimport timers from 'node:timers/promises';\n\nexport namespace Logger {\n export type Level<T extends string> =\n | 'all'\n | 'none'\n | T[]\n | { from: T; to?: T }\n | { from?: T; to: T }\n | { from: T; to: T };\n\n export interface Options<T extends string> {\n levels: T[];\n transports?: {\n /**\n * 接收日志。内置方案汇聚在 `Logger.transports` 属性中。用户也可以自己实现\n */\n transport: LoggerTransport;\n /**\n * 日志输出等级,有以下几种传值方式:\n * - `all` 输出全部等级的日志\n * - `none` 关闭日志输出\n * - `[ ]` 输出指定的等级的日志,空数组则代表关闭日志输出\n * - `{ min?, max? }` 输出等级区间内的日志,min的分数必须<=max的分数,否则关闭日志输出\n */\n level: Level<NoInfer<T>>;\n }[];\n }\n\n export interface Log<T extends string = string> {\n timestamp: Date;\n level: T;\n text: string;\n }\n}\n\nexport abstract class Logger<T extends string> {\n static transports = transports;\n\n static create = <T extends string>(\n opts: Logger.Options<T>,\n ): Logger<T> & { [K in T]: (text: string, ...args: any[]) => void } => {\n // @ts-expect-error\n return new Logger(opts);\n };\n\n protected readonly levels: T[];\n protected readonly logs: Logger.Log<T>[] = [];\n protected transportAndLevels: { transport: LoggerTransport; levels: T[] }[];\n protected timer?: NodeJS.Timeout;\n\n readonly transports: {\n add(opts: { transport: LoggerTransport; level: Logger.Level<T> }): void;\n remove(strip: (transport: LoggerTransport, levels: T[]) => boolean): void;\n };\n\n constructor(opts: Logger.Options<T>) {\n this.levels = opts.levels;\n this.transportAndLevels = (opts.transports || []).map(({ transport, level }) => {\n return {\n transport,\n levels: this.transformLevel(level),\n };\n });\n this.levels.forEach((level) => {\n Object.defineProperty(this, level, {\n value: this.log.bind(this, level),\n });\n });\n\n this.transports = {\n add: (opts) => {\n this.transportAndLevels.push({\n transport: opts.transport,\n levels: this.transformLevel(opts.level),\n });\n },\n remove: (strip) => {\n this.transportAndLevels = this.transportAndLevels.filter(\n ({ transport, levels }) => {\n return !strip(transport, levels);\n },\n );\n },\n };\n }\n\n /**\n * 保证日志(异步)输送完毕\n */\n async complete() {\n while (true) {\n if (!this.timer) return;\n if (!this.logs.length) return;\n await timers.setTimeout(50);\n }\n }\n\n /**\n * 统计某个级别有几个消费实例\n */\n countTransports(level: T): number {\n let counter = 0;\n for (const { levels } of this.transportAndLevels) {\n if (levels.includes(level)) ++counter;\n }\n return counter;\n }\n\n protected log(level: T, text: string, ...args: any[]) {\n this.logs.push({\n timestamp: new Date(),\n text: util.format(text, ...args),\n level,\n });\n this.timer ||= setTimeout(async () => {\n await this.consume();\n this.timer = undefined;\n });\n }\n\n protected async consume() {\n let log = this.logs.shift();\n while (log) {\n const targetLevel = log.level;\n await Promise.all(\n this.transportAndLevels.map(async ({ transport, levels }) => {\n if (levels.includes(targetLevel)) {\n await transport.consume(log!);\n }\n }),\n );\n log = this.logs.shift();\n }\n }\n\n protected transformLevel(level: Logger.Level<T>): T[] {\n if (typeof level !== 'object') {\n return level === 'all' ? [...this.levels] : [];\n }\n if (Array.isArray(level)) return [...new Set(level)];\n\n const min = level.from ? this.levels.findIndex((l) => l === level.from) : 0;\n const max = level.to\n ? this.levels.findIndex((l) => l === level.to) + 1\n : this.levels.length;\n return this.levels.slice(min, max);\n }\n}\n"],"mappings":";AAAA,OAAO,UAAU;AAGV,IAAe,kBAAf,MAA+B;AAAA;AAAA;AAAA;AAAA,EAM1B,WAAW,MAAY;AAC/B,WAAO;AAAA,MACL,MAAM,KAAK,YAAY,EAAE,SAAS;AAAA,MAClC,QAAQ,KAAK,SAAS,IAAI,GAAG,SAAS,EAAE,SAAS,GAAG,GAAG;AAAA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AW,OAAO,MAAM;AAC3D,cAAI,OAAO,SAAS,WAAW,GAAG;AAChC,kBAAM,UAAU,QAAQ,GAAI;AAAA,UAC9B;AAAA,QACF,CAAC;AAAA,MACH;AACA,YAAM,KAAK,KAAK,MAAM;AAAA,IACxB;AAAA,EACF;AAAA,EAEU,eAAe,OAA6B;AACpD,QAAI,OAAO,UAAU,UAAU;AAC7B,aAAO,UAAU,QAAQ,CAAC,GAAG,KAAK,MAAM,IAAI,CAAC;AAAA,IAC/C;AACA,QAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,CAAC,GAAG,IAAI,IAAI,KAAK,CAAC;AAEnD,UAAM,MAAM,MAAM,OAAO,KAAK,OAAO,UAAU,CAAC,MAAM,MAAM,MAAM,IAAI,IAAI;AAC1E,UAAM,MAAM,MAAM,KACd,KAAK,OAAO,UAAU,CAAC,MAAM,MAAM,MAAM,EAAE,IAAI,IAC/C,KAAK,OAAO;AAChB,WAAO,KAAK,OAAO,MAAM,KAAK,GAAG;AAAA,EACnC;AACF;","names":["opts"]}
package/package.json CHANGED
@@ -1,15 +1,8 @@
1
1
  {
2
2
  "name": "@aomex/logger",
3
- "version": "0.0.23",
4
- "description": "web request log",
5
- "keywords": [
6
- "api-request-logger"
7
- ],
8
- "repository": "git@github.com:aomex/aomex.git",
9
- "homepage": "https://aomex.js.org",
10
- "license": "MIT",
3
+ "version": "3.17.0",
4
+ "description": "aomex日志收集",
11
5
  "type": "module",
12
- "sideEffects": false,
13
6
  "types": "dist/index.d.ts",
14
7
  "exports": {
15
8
  ".": {
@@ -18,6 +11,9 @@
18
11
  },
19
12
  "./package.json": "./package.json"
20
13
  },
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
21
17
  "files": [
22
18
  "dist",
23
19
  "LICENSE",
@@ -25,24 +21,11 @@
25
21
  "README.md",
26
22
  "CHANGELOG.md"
27
23
  ],
28
- "publishConfig": {
29
- "access": "public"
30
- },
31
- "peerDependencies": {
32
- "@aomex/core": "^0.0.27",
33
- "@aomex/web": "^0.0.28"
34
- },
35
- "dependencies": {
36
- "pretty-time": "^1.1.0",
37
- "@aomex/internal-tools": "^0.0.27"
38
- },
39
- "devDependencies": {
40
- "@aomex/core": "^0.0.27",
41
- "@aomex/web": "^0.0.28",
42
- "@types/pretty-time": "^1.1.2",
43
- "strip-ansi": "^7.0.1"
24
+ "repository": "git@github.com:aomex/aomex.git",
25
+ "homepage": "https://aomex.js.org",
26
+ "license": "MIT",
27
+ "engines": {
28
+ "node": "^20.13.0 || ^22"
44
29
  },
45
- "scripts": {
46
- "test": "vitest"
47
- }
30
+ "scripts": {}
48
31
  }