@tachybase/logger 0.23.8

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.
@@ -0,0 +1,9 @@
1
+
2
+ 
3
+ > @tachybase/logger@0.23.7 build /Users/seal/Documents/projects/tachybase/packages/logger
4
+ > tachybase-build --no-dts @tachybase/logger
5
+
6
+ The CJS build of Vite's Node API is deprecated. See https://vite.dev/guide/troubleshooting.html#vite-cjs-node-api-deprecated for more details.
7
+ @tachybase/logger: logger build start
8
+ @tachybase/logger: build cjs
9
+
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2023-2024] [Tachybase team]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,4 @@
1
+ export declare const getLoggerLevel: () => string;
2
+ export declare const getLoggerFilePath: (...paths: string[]) => string;
3
+ export declare const getLoggerTransport: () => ("console" | "file" | "dailyRotateFile")[];
4
+ export declare const getLoggerFormat: () => "logfmt" | "json" | "delimiter" | "console";
package/lib/config.js ADDED
@@ -0,0 +1,50 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var config_exports = {};
30
+ __export(config_exports, {
31
+ getLoggerFilePath: () => getLoggerFilePath,
32
+ getLoggerFormat: () => getLoggerFormat,
33
+ getLoggerLevel: () => getLoggerLevel,
34
+ getLoggerTransport: () => getLoggerTransport
35
+ });
36
+ module.exports = __toCommonJS(config_exports);
37
+ var import_path = __toESM(require("path"));
38
+ const getLoggerLevel = /* @__PURE__ */ __name(() => process.env.LOGGER_LEVEL || (process.env.APP_ENV === "development" ? "debug" : "info"), "getLoggerLevel");
39
+ const getLoggerFilePath = /* @__PURE__ */ __name((...paths) => {
40
+ return import_path.default.resolve(process.env.LOGGER_BASE_PATH || import_path.default.resolve(process.cwd(), "storage", "logs"), ...paths);
41
+ }, "getLoggerFilePath");
42
+ const getLoggerTransport = /* @__PURE__ */ __name(() => (process.env.LOGGER_TRANSPORT || "console,dailyRotateFile").split(","), "getLoggerTransport");
43
+ const getLoggerFormat = /* @__PURE__ */ __name(() => process.env.LOGGER_FORMAT || (process.env.APP_ENV === "development" ? "console" : "json"), "getLoggerFormat");
44
+ // Annotate the CommonJS export names for ESM import in node:
45
+ 0 && (module.exports = {
46
+ getLoggerFilePath,
47
+ getLoggerFormat,
48
+ getLoggerLevel,
49
+ getLoggerTransport
50
+ });
@@ -0,0 +1,12 @@
1
+ import Koa from 'koa';
2
+ import { LoggerOptions } from './create-logger';
3
+ export interface AppLoggerOptions extends LoggerOptions {
4
+ skip?: (ctx?: any) => Promise<boolean>;
5
+ requestWhitelist?: string[];
6
+ responseWhitelist?: string[];
7
+ }
8
+ export declare function createAppLogger(options?: AppLoggerOptions): {
9
+ instance: import("winston").Logger;
10
+ middleware: (ctx: Koa.Context, next: Koa.Next) => Promise<any>;
11
+ };
12
+ export default createAppLogger;
@@ -0,0 +1,93 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var create_app_logger_exports = {};
20
+ __export(create_app_logger_exports, {
21
+ createAppLogger: () => createAppLogger,
22
+ default: () => create_app_logger_default
23
+ });
24
+ module.exports = __toCommonJS(create_app_logger_exports);
25
+ var import_crypto = require("crypto");
26
+ var import_lodash = require("lodash");
27
+ var import_create_logger = require("./create-logger");
28
+ const defaultRequestWhitelist = [
29
+ "action",
30
+ "header.x-role",
31
+ "header.x-hostname",
32
+ "header.x-timezone",
33
+ "header.x-locale",
34
+ "referer"
35
+ ];
36
+ const defaultResponseWhitelist = ["status"];
37
+ function createAppLogger(options = {}) {
38
+ const {
39
+ skip,
40
+ requestWhitelist = defaultRequestWhitelist,
41
+ responseWhitelist = defaultResponseWhitelist,
42
+ ...others
43
+ } = options;
44
+ const instance = (0, import_create_logger.createLogger)(others);
45
+ const middleware = /* @__PURE__ */ __name(async (ctx, next) => {
46
+ var _a, _b, _c, _d;
47
+ if (skip && await skip(ctx)) {
48
+ return next();
49
+ }
50
+ const logger = ctx.app["logger"];
51
+ const startTime = Date.now();
52
+ const info = {
53
+ level: "info",
54
+ message: `END: ${ctx.method} ${ctx.url}`,
55
+ req: ctx.request.toJSON()
56
+ };
57
+ ctx.reqId = ctx.req["id"] = (0, import_crypto.randomUUID)();
58
+ ctx.logger = ctx.log = logger.child({ reqId: ctx.reqId });
59
+ ctx.logger.info(`BEGIN: ${ctx.method} ${ctx.url}`);
60
+ let error;
61
+ try {
62
+ await next();
63
+ } catch (e) {
64
+ error = e;
65
+ } finally {
66
+ info["res"] = ctx.response.toJSON();
67
+ if (Math.floor(ctx.status / 100) == 5) {
68
+ info.level = "error";
69
+ info["errors"] = ((_a = ctx.body) == null ? void 0 : _a["errors"]) || ctx.body;
70
+ } else if (Math.floor(ctx.status / 100) == 4) {
71
+ info.level = "warn";
72
+ info["errors"] = ((_b = ctx.body) == null ? void 0 : _b["errors"]) || ctx.body;
73
+ }
74
+ info["responseTime"] = Date.now() - startTime;
75
+ if (ctx.action) {
76
+ info["req"]["action"] = (_d = (_c = ctx.action) == null ? void 0 : _c.toJSON) == null ? void 0 : _d.call(_c);
77
+ }
78
+ info["req"] = (0, import_lodash.pick)(info["req"], requestWhitelist);
79
+ info["res"] = (0, import_lodash.pick)(info["res"], responseWhitelist);
80
+ ctx.logger.log(info);
81
+ }
82
+ if (error) {
83
+ throw error;
84
+ }
85
+ }, "middleware");
86
+ return { instance, middleware };
87
+ }
88
+ __name(createAppLogger, "createAppLogger");
89
+ var create_app_logger_default = createAppLogger;
90
+ // Annotate the CommonJS export names for ESM import in node:
91
+ 0 && (module.exports = {
92
+ createAppLogger
93
+ });
@@ -0,0 +1,15 @@
1
+ import winston, { Logger } from 'winston';
2
+ import 'winston-daily-rotate-file';
3
+ export declare function getLoggerLevel(): string;
4
+ export declare function getLoggerFilePath(...paths: string[]): string;
5
+ declare const Transports: {
6
+ console(options: any): winston.transports.ConsoleTransportInstance;
7
+ dailyRotateFile(options?: any): import("winston-daily-rotate-file");
8
+ };
9
+ type WinstonTransport = string | string[] | winston.transport | winston.transport[];
10
+ interface LoggerOptions extends Omit<winston.LoggerOptions, 'transports'> {
11
+ transports?: WinstonTransport;
12
+ }
13
+ declare function createLogger(options?: LoggerOptions): winston.Logger;
14
+ export { createLogger, Logger, Transports };
15
+ export type { LoggerOptions };
@@ -0,0 +1,104 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var create_logger_exports = {};
30
+ __export(create_logger_exports, {
31
+ Logger: () => import_winston.Logger,
32
+ Transports: () => Transports,
33
+ createLogger: () => createLogger,
34
+ getLoggerFilePath: () => getLoggerFilePath,
35
+ getLoggerLevel: () => getLoggerLevel
36
+ });
37
+ module.exports = __toCommonJS(create_logger_exports);
38
+ var import_path = __toESM(require("path"));
39
+ var import_winston = __toESM(require("winston"));
40
+ var import_winston_daily_rotate_file = require("winston-daily-rotate-file");
41
+ const { combine, timestamp, colorize, simple } = import_winston.format;
42
+ function getLoggerLevel() {
43
+ return process.env.LOGGER_LEVEL || "info";
44
+ }
45
+ __name(getLoggerLevel, "getLoggerLevel");
46
+ function getLoggerFilePath(...paths) {
47
+ return import_path.default.resolve(process.env.LOGGER_BASE_PATH || import_path.default.resolve(process.cwd(), "storage", "logs"), ...paths);
48
+ }
49
+ __name(getLoggerFilePath, "getLoggerFilePath");
50
+ const Transports = {
51
+ console(options) {
52
+ return new import_winston.default.transports.Console({
53
+ format: combine(simple(), colorize()),
54
+ ...options
55
+ });
56
+ },
57
+ dailyRotateFile(options = {}) {
58
+ let dirname = getLoggerFilePath();
59
+ if (!import_path.default.isAbsolute(dirname)) {
60
+ dirname = import_path.default.resolve(process.cwd(), dirname);
61
+ }
62
+ return new import_winston.default.transports.DailyRotateFile({
63
+ dirname,
64
+ level: getLoggerLevel(),
65
+ filename: "tachybase-%DATE%.log",
66
+ datePattern: "YYYY-MM-DD-HH",
67
+ maxFiles: "14d",
68
+ ...options
69
+ });
70
+ }
71
+ };
72
+ function toArr(value) {
73
+ if (Array.isArray(value)) {
74
+ return value;
75
+ }
76
+ return value ? value.split(",") : [];
77
+ }
78
+ __name(toArr, "toArr");
79
+ function createLogger(options = {}) {
80
+ const transports = toArr((options == null ? void 0 : options.transports) || ["console", "dailyRotateFile"]).map((t) => {
81
+ if (typeof t === "string") {
82
+ return Transports[t]();
83
+ }
84
+ return t;
85
+ }).filter((t) => t);
86
+ const logger = import_winston.default.createLogger({
87
+ level: getLoggerLevel(),
88
+ levels: import_winston.default.config.cli.levels,
89
+ format: combine(timestamp(), import_winston.format.errors({ stack: true }), import_winston.format.json(), colorize()),
90
+ ...options,
91
+ transports
92
+ });
93
+ import_winston.default.addColors(import_winston.default.config.cli.colors);
94
+ return logger;
95
+ }
96
+ __name(createLogger, "createLogger");
97
+ // Annotate the CommonJS export names for ESM import in node:
98
+ 0 && (module.exports = {
99
+ Logger,
100
+ Transports,
101
+ createLogger,
102
+ getLoggerFilePath,
103
+ getLoggerLevel
104
+ });
@@ -0,0 +1,10 @@
1
+ import winston from 'winston';
2
+ import { LoggerOptions } from './logger';
3
+ export declare const getFormat: (format?: LoggerOptions["format"]) => winston.Logform.Format;
4
+ export declare const colorFormat: winston.Logform.Format;
5
+ export declare const stripColorFormat: winston.Logform.Format;
6
+ export declare const logfmtFormat: winston.Logform.Format;
7
+ export declare const consoleFormat: winston.Logform.Format;
8
+ export declare const delimiterFormat: winston.Logform.Format;
9
+ export declare const escapeFormat: winston.Logform.Format;
10
+ export declare const sortFormat: winston.Logform.Format;
package/lib/format.js ADDED
@@ -0,0 +1,169 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var format_exports = {};
30
+ __export(format_exports, {
31
+ colorFormat: () => colorFormat,
32
+ consoleFormat: () => consoleFormat,
33
+ delimiterFormat: () => delimiterFormat,
34
+ escapeFormat: () => escapeFormat,
35
+ getFormat: () => getFormat,
36
+ logfmtFormat: () => logfmtFormat,
37
+ sortFormat: () => sortFormat,
38
+ stripColorFormat: () => stripColorFormat
39
+ });
40
+ module.exports = __toCommonJS(format_exports);
41
+ var import_chalk = __toESM(require("chalk"));
42
+ var import_lodash = require("lodash");
43
+ var import_winston = __toESM(require("winston"));
44
+ var import_config = require("./config");
45
+ const DEFAULT_DELIMITER = "|";
46
+ const colorize = {};
47
+ const getFormat = /* @__PURE__ */ __name((format) => {
48
+ const configFormat = format || (0, import_config.getLoggerFormat)();
49
+ let logFormat;
50
+ switch (configFormat) {
51
+ case "console":
52
+ logFormat = import_winston.default.format.combine(consoleFormat);
53
+ break;
54
+ case "logfmt":
55
+ logFormat = logfmtFormat;
56
+ break;
57
+ case "delimiter":
58
+ logFormat = import_winston.default.format.combine(escapeFormat, delimiterFormat);
59
+ break;
60
+ case "json":
61
+ logFormat = import_winston.default.format.combine(import_winston.default.format.json({ deterministic: false }));
62
+ break;
63
+ default:
64
+ return import_winston.default.format.combine(format);
65
+ }
66
+ return import_winston.default.format.combine(sortFormat, logFormat);
67
+ }, "getFormat");
68
+ const colorFormat = import_winston.default.format((info) => {
69
+ Object.entries(info).forEach(([k, v]) => {
70
+ var _a;
71
+ const level = info["level"];
72
+ if (colorize[k]) {
73
+ info[k] = colorize[k](v);
74
+ return;
75
+ }
76
+ if ((_a = colorize[level]) == null ? void 0 : _a[k]) {
77
+ info[k] = colorize[level][k](v);
78
+ return;
79
+ }
80
+ });
81
+ return info;
82
+ })();
83
+ const stripColorFormat = import_winston.default.format((info) => {
84
+ Object.entries(info).forEach(([k, v]) => {
85
+ if (typeof v !== "string") {
86
+ return;
87
+ }
88
+ const regex = new RegExp(`\\x1b\\[\\d+m`, "g");
89
+ info[k] = v.replace(regex, "");
90
+ });
91
+ return info;
92
+ })();
93
+ const logfmtFormat = import_winston.default.format.printf(
94
+ (info) => Object.entries(info).map(([k, v]) => {
95
+ if (typeof v === "object") {
96
+ try {
97
+ v = JSON.stringify(v);
98
+ } catch (error) {
99
+ v = String(v);
100
+ }
101
+ }
102
+ if (v === void 0 || v === null) {
103
+ v = "";
104
+ }
105
+ return `${k}=${v}`;
106
+ }).join(" ")
107
+ );
108
+ const consoleFormat = import_winston.default.format.printf((info) => {
109
+ const keys = ["level", "timestamp", "message"];
110
+ Object.entries(info).forEach(([k, v]) => {
111
+ if (typeof v === "object") {
112
+ if ((0, import_lodash.isEmpty)(v)) {
113
+ info[k] = "";
114
+ return;
115
+ }
116
+ try {
117
+ info[k] = JSON.stringify(v);
118
+ } catch (error) {
119
+ info[k] = String(v);
120
+ }
121
+ }
122
+ if (v === void 0 || v === null) {
123
+ info[k] = "";
124
+ }
125
+ });
126
+ const tags = Object.entries(info).filter(([k, v]) => !keys.includes(k) && v).map(([k, v]) => `${k}=${v}`).join(" ");
127
+ const level = info.level.padEnd(5, " ");
128
+ const message = info.message.padEnd(44, " ");
129
+ const color = {
130
+ error: import_chalk.default.red,
131
+ warn: import_chalk.default.yellow,
132
+ info: import_chalk.default.green,
133
+ debug: import_chalk.default.blue
134
+ }[info.level] || import_chalk.default.white;
135
+ const colorized = message.startsWith("Executing") ? color(`${info.timestamp} [${level}]`) + ` ${message}` : color(`${info.timestamp} [${level}] ${message}`);
136
+ return `${colorized} ${tags}`;
137
+ });
138
+ const delimiterFormat = import_winston.default.format.printf(
139
+ (info) => Object.entries(info).map(([, v]) => {
140
+ if (typeof v === "object") {
141
+ try {
142
+ return JSON.stringify(v);
143
+ } catch (error) {
144
+ return String(v);
145
+ }
146
+ }
147
+ return v;
148
+ }).join(DEFAULT_DELIMITER)
149
+ );
150
+ const escapeFormat = import_winston.default.format((info) => {
151
+ let { message } = info;
152
+ if (typeof message === "string" && message.includes(DEFAULT_DELIMITER)) {
153
+ message = message.replace(/"/g, '\\"');
154
+ message = `"${message}"`;
155
+ }
156
+ return { ...info, message };
157
+ })();
158
+ const sortFormat = import_winston.default.format((info) => ({ level: info.level, ...info }))();
159
+ // Annotate the CommonJS export names for ESM import in node:
160
+ 0 && (module.exports = {
161
+ colorFormat,
162
+ consoleFormat,
163
+ delimiterFormat,
164
+ escapeFormat,
165
+ getFormat,
166
+ logfmtFormat,
167
+ sortFormat,
168
+ stripColorFormat
169
+ });
package/lib/index.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ export * from './config';
2
+ export * from './logger';
3
+ export * from './system-logger';
4
+ export * from './request-logger';
5
+ export * from './transports';
package/lib/index.js ADDED
@@ -0,0 +1,29 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __copyProps = (to, from, except, desc) => {
6
+ if (from && typeof from === "object" || typeof from === "function") {
7
+ for (let key of __getOwnPropNames(from))
8
+ if (!__hasOwnProp.call(to, key) && key !== except)
9
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
10
+ }
11
+ return to;
12
+ };
13
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
14
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
15
+ var src_exports = {};
16
+ module.exports = __toCommonJS(src_exports);
17
+ __reExport(src_exports, require("./config"), module.exports);
18
+ __reExport(src_exports, require("./logger"), module.exports);
19
+ __reExport(src_exports, require("./system-logger"), module.exports);
20
+ __reExport(src_exports, require("./request-logger"), module.exports);
21
+ __reExport(src_exports, require("./transports"), module.exports);
22
+ // Annotate the CommonJS export names for ESM import in node:
23
+ 0 && (module.exports = {
24
+ ...require("./config"),
25
+ ...require("./logger"),
26
+ ...require("./system-logger"),
27
+ ...require("./request-logger"),
28
+ ...require("./transports")
29
+ });
@@ -0,0 +1,12 @@
1
+ import winston, { Logger } from 'winston';
2
+ import 'winston-daily-rotate-file';
3
+ interface LoggerOptions extends Omit<winston.LoggerOptions, 'transports' | 'format'> {
4
+ dirname?: string;
5
+ filename?: string;
6
+ format?: 'logfmt' | 'json' | 'delimiter' | 'console' | winston.Logform.Format;
7
+ transports?: ('console' | 'file' | 'dailyRotateFile' | winston.transport)[];
8
+ }
9
+ export declare const createLogger: (options: LoggerOptions) => winston.Logger;
10
+ export declare const createConsoleLogger: (options?: winston.LoggerOptions) => winston.Logger;
11
+ export { Logger };
12
+ export type { LoggerOptions };
package/lib/logger.js ADDED
@@ -0,0 +1,72 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var logger_exports = {};
30
+ __export(logger_exports, {
31
+ Logger: () => import_winston.Logger,
32
+ createConsoleLogger: () => createConsoleLogger,
33
+ createLogger: () => createLogger
34
+ });
35
+ module.exports = __toCommonJS(logger_exports);
36
+ var import_winston = __toESM(require("winston"));
37
+ var import_winston_daily_rotate_file = require("winston-daily-rotate-file");
38
+ var import_config = require("./config");
39
+ var import_format = require("./format");
40
+ var import_transports = require("./transports");
41
+ const createLogger = /* @__PURE__ */ __name((options) => {
42
+ if (process.env.GITHUB_ACTIONS) {
43
+ return createConsoleLogger();
44
+ }
45
+ const { format, ...rest } = options;
46
+ const winstonOptions = {
47
+ level: (0, import_config.getLoggerLevel)(),
48
+ ...rest,
49
+ transports: (0, import_transports.getTransports)(options)
50
+ };
51
+ return import_winston.default.createLogger(winstonOptions);
52
+ }, "createLogger");
53
+ const createConsoleLogger = /* @__PURE__ */ __name((options) => {
54
+ const { format, ...rest } = options || {};
55
+ return import_winston.default.createLogger({
56
+ level: (0, import_config.getLoggerLevel)(),
57
+ format: import_winston.default.format.combine(
58
+ import_winston.default.format.timestamp({
59
+ format: "YYYY-MM-DD HH:mm:ss"
60
+ }),
61
+ format || import_format.consoleFormat
62
+ ),
63
+ ...rest || {},
64
+ transports: [new import_winston.default.transports.Console()]
65
+ });
66
+ }, "createConsoleLogger");
67
+ // Annotate the CommonJS export names for ESM import in node:
68
+ 0 && (module.exports = {
69
+ Logger,
70
+ createConsoleLogger,
71
+ createLogger
72
+ });
@@ -0,0 +1,7 @@
1
+ import { LoggerOptions } from './logger';
2
+ export interface RequestLoggerOptions extends LoggerOptions {
3
+ skip?: (ctx?: any) => Promise<boolean>;
4
+ requestWhitelist?: string[];
5
+ responseWhitelist?: string[];
6
+ }
7
+ export declare const requestLogger: (appName: string, options?: RequestLoggerOptions) => (ctx: any, next: any) => Promise<void>;
@@ -0,0 +1,98 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var request_logger_exports = {};
20
+ __export(request_logger_exports, {
21
+ requestLogger: () => requestLogger
22
+ });
23
+ module.exports = __toCommonJS(request_logger_exports);
24
+ var import_lodash = require("lodash");
25
+ var import_package = require("../package.json");
26
+ var import_config = require("./config");
27
+ var import_logger = require("./logger");
28
+ const defaultRequestWhitelist = [
29
+ "action",
30
+ "header.x-role",
31
+ "header.x-hostname",
32
+ "header.x-timezone",
33
+ "header.x-locale",
34
+ "referer"
35
+ ];
36
+ const defaultResponseWhitelist = ["status"];
37
+ const requestLogger = /* @__PURE__ */ __name((appName, options) => {
38
+ const requestLogger2 = (0, import_logger.createLogger)({
39
+ dirname: (0, import_config.getLoggerFilePath)(appName),
40
+ filename: "request",
41
+ ...options
42
+ });
43
+ return async (ctx, next) => {
44
+ var _a, _b, _c, _d, _e, _f, _g, _h;
45
+ const reqId = ctx.reqId;
46
+ const path = /^\/api\/(.+):(.+)/.exec(ctx.path);
47
+ const contextLogger = ctx.app.log.child({ reqId, module: path == null ? void 0 : path[1], submodule: path == null ? void 0 : path[2] });
48
+ ctx.logger = ctx.log = contextLogger;
49
+ const startTime = Date.now();
50
+ const requestInfo = {
51
+ method: ctx.method,
52
+ path: ctx.url
53
+ };
54
+ requestLogger2.info({
55
+ message: `request ${ctx.method} ${ctx.url}`,
56
+ ...requestInfo,
57
+ req: (0, import_lodash.pick)(ctx.request.toJSON(), (options == null ? void 0 : options.requestWhitelist) || defaultRequestWhitelist),
58
+ action: (_b = (_a = ctx.action) == null ? void 0 : _a.toJSON) == null ? void 0 : _b.call(_a),
59
+ app: appName,
60
+ reqId
61
+ });
62
+ let error;
63
+ try {
64
+ await next();
65
+ } catch (e) {
66
+ error = e;
67
+ } finally {
68
+ const cost = Date.now() - startTime;
69
+ const status = ctx.status;
70
+ const info = {
71
+ message: `response ${ctx.url}`,
72
+ ...requestInfo,
73
+ res: (0, import_lodash.pick)(ctx.response.toJSON(), (options == null ? void 0 : options.responseWhitelist) || defaultResponseWhitelist),
74
+ action: (_d = (_c = ctx.action) == null ? void 0 : _c.toJSON) == null ? void 0 : _d.call(_c),
75
+ userId: (_f = (_e = ctx.auth) == null ? void 0 : _e.user) == null ? void 0 : _f.id,
76
+ status: ctx.status,
77
+ cost,
78
+ app: appName,
79
+ reqId
80
+ };
81
+ if (Math.floor(status / 100) === 5) {
82
+ requestLogger2.error({ ...info, version: import_package.version, res: ((_g = ctx.body) == null ? void 0 : _g["errors"]) || ctx.body });
83
+ } else if (Math.floor(status / 100) === 4) {
84
+ requestLogger2.warn({ ...info, version: import_package.version, res: ((_h = ctx.body) == null ? void 0 : _h["errors"]) || ctx.body });
85
+ } else {
86
+ requestLogger2.info(info);
87
+ }
88
+ }
89
+ ctx.res.setHeader("X-Request-Id", reqId);
90
+ if (error) {
91
+ throw error;
92
+ }
93
+ };
94
+ }, "requestLogger");
95
+ // Annotate the CommonJS export names for ESM import in node:
96
+ 0 && (module.exports = {
97
+ requestLogger
98
+ });
@@ -0,0 +1,18 @@
1
+ import { Logger } from 'winston';
2
+ import { LoggerOptions } from './logger';
3
+ export interface SystemLoggerOptions extends LoggerOptions {
4
+ seperateError?: boolean;
5
+ }
6
+ export type logMethod = (message: string, meta?: {
7
+ module?: string;
8
+ submodule?: string;
9
+ method?: string;
10
+ [key: string]: any;
11
+ }) => SystemLogger;
12
+ export interface SystemLogger extends Omit<Logger, 'info' | 'warn' | 'error' | 'debug'> {
13
+ info: logMethod;
14
+ warn: logMethod;
15
+ error: logMethod;
16
+ debug: logMethod;
17
+ }
18
+ export declare const createSystemLogger: (options: SystemLoggerOptions) => SystemLogger;
@@ -0,0 +1,124 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var system_logger_exports = {};
30
+ __export(system_logger_exports, {
31
+ createSystemLogger: () => createSystemLogger
32
+ });
33
+ module.exports = __toCommonJS(system_logger_exports);
34
+ var import_triple_beam = require("triple-beam");
35
+ var import_winston = __toESM(require("winston"));
36
+ var import_winston_transport = __toESM(require("winston-transport"));
37
+ var import_package = require("../package.json");
38
+ var import_format = require("./format");
39
+ var import_logger = require("./logger");
40
+ const _SystemLoggerTransport = class _SystemLoggerTransport extends import_winston_transport.default {
41
+ logger;
42
+ errorLogger;
43
+ constructor({ seperateError, filename, ...options }) {
44
+ super({ ...options, format: null });
45
+ this.logger = (0, import_logger.createLogger)({
46
+ ...options,
47
+ filename,
48
+ format: import_winston.default.format.combine(
49
+ (0, import_winston.format)((info) => seperateError && info.level === "error" ? false : info)(),
50
+ (0, import_format.getFormat)(options.format)
51
+ )
52
+ });
53
+ if (seperateError) {
54
+ this.errorLogger = (0, import_logger.createLogger)({
55
+ ...options,
56
+ filename: `${filename}_error`,
57
+ level: "error"
58
+ });
59
+ }
60
+ }
61
+ log(info, callback) {
62
+ const { level, message, reqId, app, stack, cause, [import_triple_beam.SPLAT]: args } = info;
63
+ const logger = level === "error" && this.errorLogger ? this.errorLogger : this.logger;
64
+ const { module: module2, submodule, method, ...meta } = (args == null ? void 0 : args[0]) || {};
65
+ logger.log({
66
+ level,
67
+ message,
68
+ stack,
69
+ meta,
70
+ module: module2 || info["module"] || "",
71
+ submodule: submodule || info["submodule"] || "",
72
+ method: method || "",
73
+ app,
74
+ reqId,
75
+ version: level === "error" ? import_package.version : void 0
76
+ });
77
+ if (cause) {
78
+ logger.log({
79
+ level,
80
+ message: cause.message,
81
+ stack: cause.stack,
82
+ app,
83
+ reqId
84
+ });
85
+ }
86
+ callback(null, true);
87
+ }
88
+ };
89
+ __name(_SystemLoggerTransport, "SystemLoggerTransport");
90
+ let SystemLoggerTransport = _SystemLoggerTransport;
91
+ function child(defaultRequestMetadata) {
92
+ const logger = this;
93
+ return Object.create(logger, {
94
+ write: {
95
+ value: /* @__PURE__ */ __name(function(info) {
96
+ const infoClone = Object.assign({}, defaultRequestMetadata, info);
97
+ if (info instanceof Error) {
98
+ infoClone.stack = info.stack;
99
+ infoClone.message = info.message;
100
+ infoClone.cause = info.cause;
101
+ }
102
+ logger.write(infoClone);
103
+ }, "value")
104
+ }
105
+ });
106
+ }
107
+ __name(child, "child");
108
+ const createSystemLogger = /* @__PURE__ */ __name((options) => {
109
+ const logger = import_winston.default.createLogger({
110
+ transports: [new SystemLoggerTransport(options)]
111
+ });
112
+ return new Proxy(logger, {
113
+ get(target, prop) {
114
+ if (prop === "child") {
115
+ return child.bind(target);
116
+ }
117
+ return Reflect.get(target, prop);
118
+ }
119
+ });
120
+ }, "createSystemLogger");
121
+ // Annotate the CommonJS export names for ESM import in node:
122
+ 0 && (module.exports = {
123
+ createSystemLogger
124
+ });
@@ -0,0 +1,9 @@
1
+ import winston from 'winston';
2
+ import { DailyRotateFileTransportOptions } from 'winston-daily-rotate-file';
3
+ import { LoggerOptions } from './logger';
4
+ export declare const Transports: {
5
+ console: (options?: winston.transports.ConsoleTransportOptions) => winston.transports.ConsoleTransportInstance;
6
+ file: (options?: winston.transports.FileTransportOptions) => winston.transports.FileTransportInstance;
7
+ dailyRotateFile: (options?: DailyRotateFileTransportOptions) => import("winston-daily-rotate-file");
8
+ };
9
+ export declare const getTransports: (options: LoggerOptions) => winston.transports.ConsoleTransportInstance | (import("winston-daily-rotate-file") | winston.transport)[];
@@ -0,0 +1,86 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var transports_exports = {};
30
+ __export(transports_exports, {
31
+ Transports: () => Transports,
32
+ getTransports: () => getTransports
33
+ });
34
+ module.exports = __toCommonJS(transports_exports);
35
+ var import_path = __toESM(require("path"));
36
+ var import_winston = __toESM(require("winston"));
37
+ var import_config = require("./config");
38
+ var import_format = require("./format");
39
+ const Transports = {
40
+ console: /* @__PURE__ */ __name((options) => new import_winston.default.transports.Console(options), "console"),
41
+ file: /* @__PURE__ */ __name((options) => new import_winston.default.transports.File({
42
+ maxsize: Number(process.env.LOGGER_MAX_SIZE) || 1024 * 1024 * 20,
43
+ maxFiles: Number(process.env.LOGGER_MAX_FILES) || 10,
44
+ ...options
45
+ }), "file"),
46
+ dailyRotateFile: /* @__PURE__ */ __name((options) => new import_winston.default.transports.DailyRotateFile({
47
+ maxSize: Number(process.env.LOGGER_MAX_SIZE),
48
+ maxFiles: Number(process.env.LOGGER_MAX_FILES) || "14d",
49
+ ...options
50
+ }), "dailyRotateFile")
51
+ };
52
+ const getTransports = /* @__PURE__ */ __name((options) => {
53
+ const { filename, format: _format, transports: _transports } = options;
54
+ let { dirname } = options;
55
+ const configTransports = _transports || (0, import_config.getLoggerTransport)();
56
+ const configFormat = _format || (0, import_config.getLoggerFormat)();
57
+ dirname = dirname || (0, import_config.getLoggerFilePath)();
58
+ if (!import_path.default.isAbsolute(dirname)) {
59
+ dirname = import_path.default.resolve(process.cwd(), dirname);
60
+ }
61
+ const format = import_winston.default.format.combine(
62
+ import_winston.default.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }),
63
+ (0, import_format.getFormat)(configFormat)
64
+ );
65
+ const transports = {
66
+ console: /* @__PURE__ */ __name(() => Transports.console({
67
+ format: import_winston.default.format.combine(format)
68
+ }), "console"),
69
+ file: /* @__PURE__ */ __name(() => Transports.file({
70
+ dirname,
71
+ filename: filename.includes(".log") ? filename : `${filename}.log`,
72
+ format
73
+ }), "file"),
74
+ dailyRotateFile: /* @__PURE__ */ __name(() => Transports.dailyRotateFile({
75
+ dirname,
76
+ filename: filename.includes("%DATE%") || filename.includes(".log") ? filename : `${filename}_%DATE%.log`,
77
+ format
78
+ }), "dailyRotateFile")
79
+ };
80
+ return (configTransports == null ? void 0 : configTransports.map((t) => typeof t === "string" ? transports[t]() : t)) || transports["console"]();
81
+ }, "getTransports");
82
+ // Annotate the CommonJS export names for ESM import in node:
83
+ 0 && (module.exports = {
84
+ Transports,
85
+ getTransports
86
+ });
package/package.json ADDED
@@ -0,0 +1,20 @@
1
+ {
2
+ "name": "@tachybase/logger",
3
+ "version": "0.23.8",
4
+ "description": "logging library",
5
+ "license": "Apache-2.0",
6
+ "main": "./lib/index.js",
7
+ "types": "./lib/index.d.ts",
8
+ "dependencies": {
9
+ "chalk": "^4.1.2",
10
+ "koa": "^2.15.3",
11
+ "lodash": "^4.17.21",
12
+ "triple-beam": "^1.4.1",
13
+ "winston": "^3.17.0",
14
+ "winston-daily-rotate-file": "^4.7.1",
15
+ "winston-transport": "^4.9.0"
16
+ },
17
+ "scripts": {
18
+ "build": "tachybase-build --no-dts @tachybase/logger"
19
+ }
20
+ }