@rife/logger 0.0.5-beta.3 → 0.0.5-beta.31

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/dist/env.js ADDED
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isDev = exports.isProd = void 0;
4
+ const isProd = () => process.env.NODE_ENV === 'production';
5
+ exports.isProd = isProd;
6
+ const isDev = () => !(0, exports.isProd)();
7
+ exports.isDev = isDev;
8
+ //# sourceMappingURL=env.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env.js","sourceRoot":"","sources":["../src/env.ts"],"names":[],"mappings":";;;AAAO,MAAM,MAAM,GAAG,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY,CAAC;AAArD,QAAA,MAAM,UAA+C;AAE3D,MAAM,KAAK,GAAG,GAAG,EAAE,CAAC,CAAC,IAAA,cAAM,GAAE,CAAC;AAAxB,QAAA,KAAK,SAAmB"}
package/dist/index.js CHANGED
@@ -1,125 +1,5 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createLogger = exports.getTraceId = exports.runInTrace = exports.getNewTraceId = exports.winston = void 0;
4
3
  const tslib_1 = require("tslib");
5
- const path_1 = tslib_1.__importDefault(require("path"));
6
- const async_hooks_1 = require("async_hooks");
7
- const chalk_1 = tslib_1.__importDefault(require("chalk"));
8
- const nanoid_1 = require("nanoid");
9
- const winston_1 = tslib_1.__importDefault(require("winston"));
10
- exports.winston = winston_1.default;
11
- const safe_stable_stringify_1 = tslib_1.__importDefault(require("safe-stable-stringify"));
12
- require("winston-daily-rotate-file");
13
- const als = new async_hooks_1.AsyncLocalStorage();
14
- const isDev = () => process.env.NODE_ENV === 'development';
15
- const isProd = () => !isDev();
16
- // https://github.com/CyberAP/nanoid-dictionary/blob/master/src/nolookalikes.js
17
- exports.getNewTraceId = (0, nanoid_1.customAlphabet)('346789ABCDEFGHJKLMNPQRTUVWXYabcdefghijkmnpqrtwxyz', 5);
18
- function runInTrace(fn) {
19
- return als.run({ traceId: (0, exports.getNewTraceId)() }, fn);
20
- }
21
- exports.runInTrace = runInTrace;
22
- function getTraceId() {
23
- return als.getStore()?.traceId;
24
- }
25
- exports.getTraceId = getTraceId;
26
- const levelColor = {
27
- info: chalk_1.default.green,
28
- error: chalk_1.default.redBright,
29
- warn: chalk_1.default.yellow,
30
- };
31
- const levelSymbolMap = {
32
- info: 'INF',
33
- warn: 'WRN',
34
- error: 'ERR',
35
- };
36
- // 设置traceId
37
- // https://www.npmjs.com/package/cls-rtracer
38
- const tracerFormat = (options) => winston_1.default.format.printf(info => {
39
- let traceId = getTraceId();
40
- const color = (message, chalk) => (options.writeToFile ? message : chalk(message));
41
- const levelit = (text) => {
42
- switch (info.level) {
43
- case 'info': {
44
- return color(text, levelColor.info);
45
- }
46
- case 'warn': {
47
- return color(text, levelColor.warn);
48
- }
49
- case 'error': {
50
- return color(text, levelColor.error);
51
- }
52
- }
53
- return text;
54
- };
55
- const levelSymbol = levelSymbolMap[info.level];
56
- const level = levelSymbol ? levelit(` [${levelSymbol}]`) : '';
57
- const service = info.metadata.service ? levelit(` [${info.metadata.service}]`) : '';
58
- const timestamp = options.format.time ? color(info.timestamp, chalk_1.default.gray) : '';
59
- const trace = traceId ? color(` [${traceId}]`, chalk_1.default.gray) : '';
60
- let message = info.message || '';
61
- if (typeof info?.message !== 'string') {
62
- try {
63
- if (isDev()) {
64
- message = '\n' + (0, safe_stable_stringify_1.default)(info?.message, undefined, 4);
65
- }
66
- else {
67
- message = (0, safe_stable_stringify_1.default)(info?.message, undefined, 0);
68
- }
69
- }
70
- catch (e) {
71
- message = 'fail to stringify json';
72
- }
73
- }
74
- message = ' ' + message;
75
- const stack = info.metadata.stack ? color('\n' + info.metadata.stack + '\n', chalk_1.default.gray) : '';
76
- return `${timestamp}${trace}${level}${service}${message}${stack}`;
77
- });
78
- function createLogger(options) {
79
- let transports = [];
80
- let config = {
81
- writeToConsole: options?.writeToConsole ?? isDev(),
82
- writeToFile: options?.writeToFile ?? isProd(),
83
- dirname: options?.dirname || path_1.default.join(process.cwd(), './logs/'),
84
- filename: options?.filename || 'server',
85
- format: {
86
- time: options?.format?.time ?? true,
87
- },
88
- };
89
- if (config.writeToFile) {
90
- transports.push(new winston_1.default.transports.DailyRotateFile({
91
- // https://www.npmjs.com/package/winston-daily-rotate-file
92
- filename: config.filename,
93
- dirname: config.dirname,
94
- datePattern: 'YYYY-MM-DD',
95
- maxFiles: '30d',
96
- extension: '.log',
97
- }));
98
- }
99
- if (config.writeToConsole) {
100
- transports.push(new winston_1.default.transports.Console());
101
- }
102
- const { combine, timestamp, colorize, errors, metadata, splat, json } = winston_1.default.format;
103
- const timeFormat = isProd() ? 'YYYY-MM-DD HH:mm:ss.SSS' : 'HH:mm:ss.SSS';
104
- let format = [
105
- errors({ stack: true }),
106
- metadata(),
107
- timestamp({ format: timeFormat }),
108
- splat(),
109
- tracerFormat(config),
110
- ];
111
- if (!config.writeToFile) {
112
- format.push(colorize());
113
- }
114
- const instance = winston_1.default.createLogger({
115
- format: combine(...format),
116
- transports,
117
- });
118
- const logger = {
119
- info: instance.info.bind(instance),
120
- warn: instance.warn.bind(instance),
121
- error: instance.error.bind(instance),
122
- };
123
- return { logger, instance };
124
- }
125
- exports.createLogger = createLogger;
4
+ tslib_1.__exportStar(require("./trace"), exports);
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,kDAAwB"}
package/dist/pino.js ADDED
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createLogger = createLogger;
4
+ const tslib_1 = require("tslib");
5
+ const pino_1 = tslib_1.__importDefault(require("pino"));
6
+ // https://github.com/pinojs/pino/blob/master/docs/api.md
7
+ const env_1 = require("./env");
8
+ const trace_1 = require("./trace");
9
+ function getPinoConfig() {
10
+ const targets = [];
11
+ if ((0, env_1.isDev)()) {
12
+ targets.push({
13
+ level: 'debug',
14
+ target: 'pino-pretty', // must be installed separately,
15
+ options: {},
16
+ });
17
+ }
18
+ targets.push({
19
+ level: 'debug',
20
+ target: './rotate',
21
+ options: { path: './.logs/' },
22
+ });
23
+ const config = {
24
+ transport: { targets },
25
+ mixin(data) {
26
+ if (!data?.traceId) {
27
+ return { traceId: (0, trace_1.getTraceId)() };
28
+ }
29
+ return {};
30
+ },
31
+ };
32
+ return config;
33
+ }
34
+ const startTime = Symbol('startTime');
35
+ function createLogger(options) {
36
+ const logger = (0, pino_1.default)({
37
+ ...getPinoConfig(),
38
+ });
39
+ const express = () => {
40
+ const { mapHttpRequest, mapHttpResponse } = require('pino-std-serializers');
41
+ return (req, res, next) => {
42
+ const response = res;
43
+ response[startTime] = response[startTime] || Date.now();
44
+ const traceId = req.headers['trace-id'] || (0, trace_1.genTraceId)();
45
+ const onComplete = () => {
46
+ res.removeListener('close', onComplete);
47
+ res.removeListener('finish', onComplete);
48
+ res.removeListener('error', onComplete);
49
+ const duration = Date.now() - response[startTime];
50
+ logger.info({ duration, request: mapHttpRequest(req).req, response: mapHttpResponse(res).res }, 'request');
51
+ };
52
+ res.on('close', onComplete);
53
+ res.on('finish', onComplete);
54
+ res.on('error', onComplete);
55
+ (0, trace_1.runInTrace)({ traceId }, next);
56
+ };
57
+ };
58
+ return { logger, express };
59
+ }
60
+ //# sourceMappingURL=pino.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pino.js","sourceRoot":"","sources":["../src/pino.ts"],"names":[],"mappings":";;AAkDA,oCA+BC;;AAjFD,wDAAwB;AACxB,yDAAyD;AAEzD,+BAA8B;AAC9B,mCAA6D;AAc7D,SAAS,aAAa;IAClB,MAAM,OAAO,GAAQ,EAAE,CAAC;IAExB,IAAI,IAAA,WAAK,GAAE,EAAE,CAAC;QACV,O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CAAC,CAAC;gBACxC,GAAG,CAAC,cAAc,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC;gBACzC,GAAG,CAAC,cAAc,CAAC,OAAO,EAAE,UAAU,CAAC,CAAC;gBACxC,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,QAAQ,CAAC,SAAS,CAAC,CAAC;gBAElD,MAAM,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,OAAO,EAAE,cAAc,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,QAAQ,EAAE,eAAe,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,SAAS,CAAC,CAAC;YAC/G,CAAC,CAAC;YAEF,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,UAAU,CAAC,CAAC;YAC5B,GAAG,CAAC,EAAE,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC;YAC7B,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,UAAU,CAAC,CAAC;YAE5B,IAAA,kBAAU,EAAC,EAAE,OAAO,EAAE,EAAE,IAAI,CAAC,CAAC;QAClC,CAAC,CAAC;IACN,CAAC,CAAC;IAEF,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;AAC/B,CAAC"}
package/dist/rotate.js ADDED
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const generator = (time, index) => {
4
+ if (!time) {
5
+ return 'server.log';
6
+ }
7
+ time = new Date(time);
8
+ const month = String(time.getMonth() + 1).padStart(2, '0');
9
+ const day = String(time.getDate()).padStart(2, '0');
10
+ if (index) {
11
+ const count = String(index).padStart(3, '0');
12
+ return `server.${time.getFullYear()}${month}${day}-${count}.log`;
13
+ }
14
+ return `server.${time.getFullYear()}${month}${day}.log`;
15
+ };
16
+ exports.default = (options) => {
17
+ const { createStream } = require('rotating-file-stream');
18
+ const { path } = options;
19
+ return createStream(generator, {
20
+ size: '50M',
21
+ maxSize: '500M',
22
+ interval: '1d',
23
+ path,
24
+ });
25
+ };
26
+ //# sourceMappingURL=rotate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rotate.js","sourceRoot":"","sources":["../src/rotate.ts"],"names":[],"mappings":";;AAMA,MAAM,SAAS,GAAG,CAAC,IAAmB,EAAE,KAAc,EAAE,EAAE;IACtD,IAAI,CAAC,IAAI,EAAE,CAAC;QACR,OAAO,YAAY,CAAC;IACxB,CAAC;IACD,IAAI,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC;IAEtB,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;IAC3D,MAAM,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;IACpD,IAAI,KAAK,EAAE,CAAC;QACR,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;QAC7C,OAAO,UAAU,IAAI,CAAC,WAAW,EAAE,GAAG,KAAK,GAAG,GAAG,IAAI,KAAK,MAAM,CAAC;IACrE,CAAC;IACD,OAAO,UAAU,IAAI,CAAC,WAAW,EAAE,GAAG,KAAK,GAAG,GAAG,MAAM,CAAC;AAC5D,CAAC,CAAC;AAEF,kBAAe,CAAC,OAAsC,EAAE,EAAE;IACtD,MAAM,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC,sBAAsB,CAA0C,CAAC;IAElG,MAAM,EAAE,IAAI,EAAE,GAAG,OAAO,CAAC;IACzB,OAAO,YAAY,CAAC,SAAS,EAAE;QAC3B,IAAI,EAAE,KAAK;QACX,OAAO,EAAE,MAAM;QACf,QAAQ,EAAE,IAAI;QACd,IAAI;KACP,CAAC,CAAC;AACP,CAAC,CAAC"}
package/dist/test.js CHANGED
@@ -2,21 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  process.env.NODE_ENV = 'development';
4
4
  // process.env.NODE_ENV = 'production';
5
- const _1 = require(".");
6
- const { logger } = (0, _1.createLogger)({ writeToFile: false, writeToConsole: true, format: { time: false } });
7
- const deep = { a: { b: { c: { g: { e: { f: 1 } } } } } };
8
- logger.info('1 %s', { a: 1 });
9
- logger.info('2 %j', deep);
10
- logger.info('3 \n%j', deep);
11
- logger.info('4 %s %s', 1, 2);
12
- logger.info('5 %o', deep);
13
- logger.info(deep);
14
- logger.warn('execed');
15
- logger.error(new Error('not found'));
16
- // import { format } from 'logform';
17
- // const jsonFormat = format.json({ space: 2 });
18
- // const info = jsonFormat.transform({
19
- // level: 'info',
20
- // message: 'my message',
21
- // });
22
- // console.log(info);
5
+ process.env.NODE_ENV = 'development';
6
+ const trace_1 = require("./trace");
7
+ console.log((0, trace_1.genTraceId)());
8
+ //# sourceMappingURL=test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"test.js","sourceRoot":"","sources":["../src/test.ts"],"names":[],"mappings":";;AAAA,OAAO,CAAC,GAAG,CAAC,QAAQ,GAAG,aAAa,CAAC;AACrC,uCAAuC;AACvC,OAAO,CAAC,GAAG,CAAC,QAAQ,GAAG,aAAa,CAAC;AAiBrC,mCAAqC;AAErC,OAAO,CAAC,GAAG,CAAC,IAAA,kBAAU,GAAE,CAAC,CAAC"}
package/dist/trace.js ADDED
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runInTrace = runInTrace;
4
+ exports.genTraceId = genTraceId;
5
+ exports.getTraceId = getTraceId;
6
+ const async_hooks_1 = require("async_hooks");
7
+ const als = new async_hooks_1.AsyncLocalStorage();
8
+ function runInTrace(data, fn) {
9
+ return als.run(data, fn);
10
+ }
11
+ function genTraceId() {
12
+ return crypto.randomUUID();
13
+ }
14
+ function getTraceId() {
15
+ return als.getStore()?.traceId;
16
+ }
17
+ //# sourceMappingURL=trace.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trace.js","sourceRoot":"","sources":["../src/trace.ts"],"names":[],"mappings":";;AAIA,gCAEC;AAED,gCAEC;AAED,gCAEC;AAdD,6CAAgD;AAEhD,MAAM,GAAG,GAAG,IAAI,+BAAiB,EAA6B,CAAC;AAE/D,SAAgB,UAAU,CAAI,IAAS,EAAE,EAAyB;IAC9D,OAAO,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;AAC7B,CAAC;AAED,SAAgB,UAAU;IACtB,OAAO,MAAM,CAAC,UAAU,EAAE,CAAC;AAC/B,CAAC;AAED,SAAgB,UAAU;IACtB,OAAO,GAAG,CAAC,QAAQ,EAAE,EAAE,OAAO,CAAC;AACnC,CAAC"}
@@ -0,0 +1,118 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createLogger = createLogger;
4
+ const tslib_1 = require("tslib");
5
+ const path_1 = tslib_1.__importDefault(require("path"));
6
+ const chalk_1 = tslib_1.__importDefault(require("chalk"));
7
+ const winston_1 = tslib_1.__importDefault(require("winston"));
8
+ const safe_stable_stringify_1 = tslib_1.__importDefault(require("safe-stable-stringify"));
9
+ require("winston-daily-rotate-file");
10
+ const env_1 = require("./env");
11
+ const trace_1 = require("./trace");
12
+ const levelColor = {
13
+ info: chalk_1.default.green,
14
+ error: chalk_1.default.redBright,
15
+ warn: chalk_1.default.yellow,
16
+ };
17
+ const levelSymbolMap = {
18
+ info: 'INF',
19
+ warn: 'WRN',
20
+ error: 'ERR',
21
+ };
22
+ // 设置traceId
23
+ // https://www.npmjs.com/package/cls-rtracer
24
+ const tracerFormat = (options) => winston_1.default.format.printf(info => {
25
+ let traceId = (0, trace_1.getTraceId)();
26
+ const color = (message, chalk) => (options.writeToFile ? message : chalk(message));
27
+ const levelit = (text) => {
28
+ switch (info.level) {
29
+ case 'info': {
30
+ return color(text, levelColor.info);
31
+ }
32
+ case 'warn': {
33
+ return color(text, levelColor.warn);
34
+ }
35
+ case 'error': {
36
+ return color(text, levelColor.error);
37
+ }
38
+ }
39
+ return text;
40
+ };
41
+ const levelSymbol = levelSymbolMap[info.level];
42
+ const level = levelSymbol ? levelit(` [${levelSymbol}]`) : '';
43
+ const service = info.metadata.service ? levelit(` [${info.metadata.service}]`) : '';
44
+ const timestamp = options.format.time ? color(info.timestamp, chalk_1.default.gray) : '';
45
+ const trace = traceId ? color(` [${traceId}]`, chalk_1.default.gray) : '';
46
+ let message = info.message || '';
47
+ if (typeof info?.message !== 'string') {
48
+ try {
49
+ if ((0, env_1.isDev)()) {
50
+ message = '\n' + (0, safe_stable_stringify_1.default)(info?.message, undefined, 4);
51
+ }
52
+ else {
53
+ message = (0, safe_stable_stringify_1.default)(info?.message, undefined, 0);
54
+ }
55
+ }
56
+ catch (e) {
57
+ message = 'fail to stringify json';
58
+ }
59
+ }
60
+ message = ' ' + message;
61
+ const stack = info.metadata.stack ? color('\n' + info.metadata.stack + '\n', chalk_1.default.gray) : '';
62
+ return `${timestamp}${trace}${level}${service}${message}${stack}`;
63
+ });
64
+ function createLogger(options) {
65
+ let transports = [];
66
+ let config = {
67
+ writeToConsole: options?.writeToConsole ?? (0, env_1.isDev)(),
68
+ writeToFile: options?.writeToFile ?? (0, env_1.isProd)(),
69
+ dirname: options?.dirname || path_1.default.join(process.cwd(), './logs/'),
70
+ filename: options?.filename || 'server',
71
+ format: {
72
+ time: options?.format?.time ?? true,
73
+ },
74
+ };
75
+ if (config.writeToFile) {
76
+ transports.push(new winston_1.default.transports.DailyRotateFile({
77
+ // https://www.npmjs.com/package/winston-daily-rotate-file
78
+ filename: config.filename,
79
+ dirname: config.dirname,
80
+ datePattern: 'YYYY-MM-DD',
81
+ maxFiles: '30d',
82
+ extension: '.log',
83
+ }));
84
+ }
85
+ if (config.writeToConsole) {
86
+ transports.push(new winston_1.default.transports.Console());
87
+ }
88
+ const { combine, timestamp, colorize, errors, metadata, splat } = winston_1.default.format;
89
+ const timeFormat = (0, env_1.isProd)() ? 'YYYY-MM-DD HH:mm:ss.SSS' : 'HH:mm:ss.SSS';
90
+ let format = [
91
+ errors({ stack: true }),
92
+ metadata(),
93
+ timestamp({ format: timeFormat }),
94
+ splat(), // https://github.com/winstonjs/logform/blob/master/splat.js
95
+ tracerFormat(config),
96
+ ];
97
+ if (!config.writeToFile) {
98
+ format.push(colorize());
99
+ }
100
+ const instance = winston_1.default.createLogger({
101
+ format: combine(...format),
102
+ transports,
103
+ });
104
+ const setMetaData = (data) => {
105
+ instance.defaultMeta = {
106
+ ...instance.defaultMeta,
107
+ ...data,
108
+ };
109
+ };
110
+ const logger = {
111
+ info: instance.info.bind(instance),
112
+ warn: instance.warn.bind(instance),
113
+ error: instance.error.bind(instance),
114
+ setMetaData,
115
+ };
116
+ return { logger };
117
+ }
118
+ //# sourceMappingURL=winston.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"winston.js","sourceRoot":"","sources":["../src/winston.ts"],"names":[],"mappings":";;AAuHA,oCA4DC;;AAnLD,wDAAwB;AAGxB,0DAA0B;AAC1B,8DAA8B;AAC9B,0FAAkD;AAClD,qCAAmC;AAEnC,+BAAsC;AACtC,mCAAqC;AAIrC,MAAM,UAAU,GAAG;IACf,IAAI,EAAE,eAAK,CAAC,KAAK;IACjB,KAAK,EAAE,eAAK,CAAC,SAAS;IACtB,IAAI,EAAE,eAAK,CAAC,MAAM;CACrB,CAAC;AAEF,MAAM,cAAc,GAAG;IACnB,IAAI,EAAE,KAAK;IACX,IAAI,EAAE,KAAK;IACX,KAAK,EAAE,KAAK;CACf,CAAC;AAEF,YAAY;AACZ,4CAA4C;AAC5C,MAAM,YAAY,GAAG,CAAC,OAA4D,EAAE,EAAE,CAClF,iBAAO,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE;IACzB,IAAI,OAAO,GAAG,IAAA,kBAAU,GAAE,CAAC;IAC3B,MAAM,KAAK,GAAG,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EAAE,OAAO,CAAC,GAAG,MAAM,CAAC;QAC1B,UAAU;KACb,CAAC,CAAC;IAEH,MAAM,WAAW,GAAG,CAAC,IAAS,EAAE,EAAE;QAC9B,QAAQ,CAAC,WAAW,GAAG;YACnB,GAAG,QAAQ,CAAC,WAAW;YACvB,GAAG,IAAI;SACV,CAAC;IACN,CAAC,CAAC;IAEF,MAAM,MAAM,GAAW;QACnB,IAAI,EAAE,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC;QAClC,IAAI,EAAE,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC;QAClC,KAAK,EAAE,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC;QACpC,WAAW;KACd,CAAC;IAEF,OAAO,EAAE,MAAM,EAAE,CAAC;AACtB,CAAC"}
package/package.json CHANGED
@@ -1,9 +1,25 @@
1
1
  {
2
2
  "name": "@rife/logger",
3
- "version": "0.0.5-beta.3",
3
+ "version": "0.0.5-beta.31",
4
4
  "description": "",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./src/index.ts",
7
+ "exports": {
8
+ ".": {
9
+ "require": "./dist/index.js"
10
+ },
11
+ "./pino": {
12
+ "require": "./dist/pino.js",
13
+ "types": "./src/pino.ts"
14
+ }
15
+ },
16
+ "typesVersions": {
17
+ "*": {
18
+ "pino": [
19
+ "./src/pino.ts"
20
+ ]
21
+ }
22
+ },
7
23
  "files": [
8
24
  "dist/**/*",
9
25
  "src/**/*",
@@ -11,10 +27,15 @@
11
27
  ],
12
28
  "dependencies": {
13
29
  "chalk": "4",
14
- "nanoid": "^3.1.30",
15
- "winston": "^3.3.3",
16
- "winston-daily-rotate-file": "^4.5.5",
17
- "@rife/config": "0.0.5-beta.3"
30
+ "pino": "^8.16.1",
31
+ "pino-http": "^8.5.1",
32
+ "pino-pretty": "^10.2.3",
33
+ "pino-std-serializers": "^6.2.2",
34
+ "rotating-file-stream": "^3.2.1",
35
+ "safe-stable-stringify": "^2.4.3",
36
+ "winston": "^3.9.0",
37
+ "winston-daily-rotate-file": "^4.7.1",
38
+ "@rife/config": "0.0.5-beta.31"
18
39
  },
19
40
  "scripts": {
20
41
  "dev": "infra dev",
package/src/env.ts ADDED
@@ -0,0 +1,3 @@
1
+ export const isProd = () => process.env.NODE_ENV === 'production';
2
+
3
+ export const isDev = () => !isProd();
package/src/index.ts CHANGED
@@ -1,187 +1 @@
1
- import path from 'path';
2
- import { AsyncLocalStorage } from 'async_hooks';
3
-
4
- import chalk from 'chalk';
5
- import { customAlphabet } from 'nanoid';
6
- import winston from 'winston';
7
- import JSONStringify from 'safe-stable-stringify';
8
- import 'winston-daily-rotate-file';
9
-
10
- export { winston };
11
-
12
- const als = new AsyncLocalStorage<{ traceId: string } & any>();
13
-
14
- const isDev = () => process.env.NODE_ENV === 'development';
15
- const isProd = () => !isDev();
16
-
17
- // https://github.com/CyberAP/nanoid-dictionary/blob/master/src/nolookalikes.js
18
- export const getNewTraceId = customAlphabet('346789ABCDEFGHJKLMNPQRTUVWXYabcdefghijkmnpqrtwxyz', 5);
19
-
20
- export function runInTrace<T>(fn: (...args: any[]) => T): T {
21
- return als.run({ traceId: getNewTraceId() }, fn);
22
- }
23
-
24
- export function getTraceId() {
25
- return als.getStore()?.traceId;
26
- }
27
-
28
- const levelColor = {
29
- info: chalk.green,
30
- error: chalk.redBright,
31
- warn: chalk.yellow,
32
- };
33
-
34
- const levelSymbolMap = {
35
- info: 'INF',
36
- warn: 'WRN',
37
- error: 'ERR',
38
- };
39
-
40
- // 设置traceId
41
- // https://www.npmjs.com/package/cls-rtracer
42
- const tracerFormat = (options: { writeToFile: boolean; format: { time: boolean } }) =>
43
- winston.format.printf(info => {
44
- let traceId = getTraceId();
45
- const color = (message: string, chalk: chalk.Chalk) => (options.writeToFile ? message : chalk(message));
46
- const levelit = (text: string) => {
47
- switch (info.level) {
48
- case 'info': {
49
- return color(text, levelColor.info);
50
- }
51
- case 'warn': {
52
- return color(text, levelColor.warn);
53
- }
54
- case 'error': {
55
- return color(text, levelColor.error);
56
- }
57
- }
58
- return text;
59
- };
60
- const levelSymbol = levelSymbolMap[info.level as keyof typeof levelSymbolMap];
61
- const level = levelSymbol ? levelit(` [${levelSymbol}]`) : '';
62
- const service = info.metadata.service ? levelit(` [${info.metadata.service}]`) : '';
63
- const timestamp = options.format.time ? color(info.timestamp, chalk.gray) : '';
64
- const trace = traceId ? color(` [${traceId}]`, chalk.gray) : '';
65
- let message = info.message || '';
66
- if (typeof info?.message !== 'string') {
67
- try {
68
- if (isDev()) {
69
- message = '\n' + JSONStringify(info?.message, undefined, 4);
70
- } else {
71
- message = JSONStringify(info?.message, undefined, 0);
72
- }
73
- } catch (e) {
74
- message = 'fail to stringify json';
75
- }
76
- }
77
- message = ' ' + message;
78
- const stack = info.metadata.stack ? color('\n' + info.metadata.stack + '\n', chalk.gray) : '';
79
- return `${timestamp}${trace}${level}${service}${message}${stack}`;
80
- });
81
-
82
- export namespace Rife {
83
- export namespace Logger {
84
- export interface Options {
85
- /**
86
- * 输出日志到console
87
- * 默认:development环境下输出,production环境下不输出
88
- */
89
- writeToConsole?: boolean;
90
-
91
- /**
92
- * 输出日志到文件
93
- * 默认:development环境下输出,production环境下不输出
94
- */
95
- writeToFile?: boolean;
96
-
97
- /**
98
- * 输出日志的文件目录
99
- * 默认:./logs/
100
- */
101
- dirname?: string;
102
-
103
- /**
104
- * 输出日志的文件名
105
- * 默认:server
106
- */
107
- filename?: string;
108
-
109
- /**
110
- * 日志输出格式
111
- */
112
- format?: {
113
- /**
114
- * 显示时间
115
- * 默认:true
116
- */
117
- time?: boolean;
118
-
119
- /**
120
- * 显示traceId
121
- * 默认:true
122
- */
123
- traceId?: boolean;
124
- };
125
- }
126
- }
127
-
128
- export interface Logger {
129
- info: winston.LeveledLogMethod;
130
- warn: winston.LeveledLogMethod;
131
- error: winston.LeveledLogMethod;
132
- }
133
- }
134
-
135
- export function createLogger(options?: Rife.Logger.Options) {
136
- let transports: winston.transport[] = [];
137
- let config = {
138
- writeToConsole: options?.writeToConsole ?? isDev(),
139
- writeToFile: options?.writeToFile ?? isProd(),
140
- dirname: options?.dirname || path.join(process.cwd(), './logs/'),
141
- filename: options?.filename || 'server',
142
- format: {
143
- time: options?.format?.time ?? true,
144
- },
145
- };
146
- if (config.writeToFile) {
147
- transports.push(
148
- new winston.transports.DailyRotateFile({
149
- // https://www.npmjs.com/package/winston-daily-rotate-file
150
- filename: config.filename,
151
- dirname: config.dirname,
152
- datePattern: 'YYYY-MM-DD',
153
- maxFiles: '30d',
154
- extension: '.log',
155
- }),
156
- );
157
- }
158
-
159
- if (config.writeToConsole) {
160
- transports.push(new winston.transports.Console());
161
- }
162
-
163
- const { combine, timestamp, colorize, errors, metadata, splat, json } = winston.format;
164
- const timeFormat = isProd() ? 'YYYY-MM-DD HH:mm:ss.SSS' : 'HH:mm:ss.SSS';
165
- let format: winston.Logform.Format[] = [
166
- errors({ stack: true }),
167
- metadata(),
168
- timestamp({ format: timeFormat }),
169
- splat(), // https://github.com/winstonjs/logform/blob/master/splat.js
170
- tracerFormat(config),
171
- ];
172
- if (!config.writeToFile) {
173
- format.push(colorize());
174
- }
175
- const instance = winston.createLogger({
176
- format: combine(...format),
177
- transports,
178
- });
179
-
180
- const logger: Rife.Logger = {
181
- info: instance.info.bind(instance),
182
- warn: instance.warn.bind(instance),
183
- error: instance.error.bind(instance),
184
- };
185
-
186
- return { logger, instance };
187
- }
1
+ export * from './trace';
package/src/pino.ts ADDED
@@ -0,0 +1,82 @@
1
+ import pino from 'pino';
2
+ // https://github.com/pinojs/pino/blob/master/docs/api.md
3
+
4
+ import { isDev } from './env';
5
+ import { genTraceId, getTraceId, runInTrace } from './trace';
6
+
7
+ export interface ILogger {
8
+ debug: pino.LogFn;
9
+ info: pino.LogFn;
10
+ warn: pino.LogFn;
11
+ error: pino.LogFn;
12
+ setData: (value: any) => any;
13
+ }
14
+
15
+ export namespace ILogger {
16
+ export interface Options {}
17
+ }
18
+
19
+ function getPinoConfig() {
20
+ const targets: any = [];
21
+
22
+ if (isDev()) {
23
+ targets.push({
24
+ level: 'debug',
25
+ target: 'pino-pretty', // must be installed separately,
26
+ options: {},
27
+ });
28
+ }
29
+
30
+ targets.push({
31
+ level: 'debug',
32
+ target: './rotate',
33
+ options: { path: './.logs/' },
34
+ });
35
+
36
+ const config: pino.LoggerOptions = {
37
+ transport: { targets },
38
+ mixin(data: any) {
39
+ if (!data?.traceId) {
40
+ return { traceId: getTraceId() };
41
+ }
42
+ return {};
43
+ },
44
+ };
45
+
46
+ return config;
47
+ }
48
+
49
+ const startTime = Symbol('startTime');
50
+
51
+ export function createLogger(options?: ILogger.Options) {
52
+ const logger = pino({
53
+ ...getPinoConfig(),
54
+ });
55
+
56
+ const express = () => {
57
+ const { mapHttpRequest, mapHttpResponse } = require('pino-std-serializers') as typeof import('pino-std-serializers');
58
+
59
+ return (req: any, res: any, next: any) => {
60
+ const response: any = res;
61
+ response[startTime] = response[startTime] || Date.now();
62
+ const traceId = req.headers['trace-id'] || genTraceId();
63
+
64
+ const onComplete = () => {
65
+ res.removeListener('close', onComplete);
66
+ res.removeListener('finish', onComplete);
67
+ res.removeListener('error', onComplete);
68
+ const duration = Date.now() - response[startTime];
69
+
70
+ logger.info({ duration, request: mapHttpRequest(req).req, response: mapHttpResponse(res).res }, 'request');
71
+ };
72
+
73
+ res.on('close', onComplete);
74
+ res.on('finish', onComplete);
75
+ res.on('error', onComplete);
76
+
77
+ runInTrace({ traceId }, next);
78
+ };
79
+ };
80
+
81
+ return { logger, express };
82
+ }
package/src/rotate.ts ADDED
@@ -0,0 +1,32 @@
1
+ import type { Options } from 'rotating-file-stream';
2
+
3
+ export interface PinoRotatingFileStreamOptions extends Options {
4
+ path: string;
5
+ }
6
+
7
+ const generator = (time: number | Date, index?: number) => {
8
+ if (!time) {
9
+ return 'server.log';
10
+ }
11
+ time = new Date(time);
12
+
13
+ const month = String(time.getMonth() + 1).padStart(2, '0');
14
+ const day = String(time.getDate()).padStart(2, '0');
15
+ if (index) {
16
+ const count = String(index).padStart(3, '0');
17
+ return `server.${time.getFullYear()}${month}${day}-${count}.log`;
18
+ }
19
+ return `server.${time.getFullYear()}${month}${day}.log`;
20
+ };
21
+
22
+ export default (options: PinoRotatingFileStreamOptions) => {
23
+ const { createStream } = require('rotating-file-stream') as typeof import('rotating-file-stream');
24
+
25
+ const { path } = options;
26
+ return createStream(generator, {
27
+ size: '50M',
28
+ maxSize: '500M',
29
+ interval: '1d',
30
+ path,
31
+ });
32
+ };
package/src/test.ts CHANGED
@@ -1,25 +1,22 @@
1
1
  process.env.NODE_ENV = 'development';
2
2
  // process.env.NODE_ENV = 'production';
3
+ process.env.NODE_ENV = 'development';
3
4
 
4
- import { createLogger } from '.';
5
+ // import { createLogger } from './winston';
5
6
 
6
- const { logger } = createLogger({ writeToFile: false, writeToConsole: true, format: { time: false } });
7
+ // const { logger } = createLogger({ writeToFile: false, writeToConsole: true, format: { time: false } });
7
8
 
8
- const deep = { a: { b: { c: { g: { e: { f: 1 } } } } } };
9
- logger.info('1 %s', { a: 1 });
10
- logger.info('2 %j', deep);
11
- logger.info('3 \n%j', deep);
12
- logger.info('4 %s %s', 1, 2);
13
- logger.info('5 %o', deep);
14
- logger.info(deep);
15
- logger.warn('execed');
16
- logger.error(new Error('not found'));
9
+ // const deep = { a: { b: { c: { g: { e: { f: 1 } } } } } };
10
+ // logger.info('1 %s', { a: 1 });
11
+ // logger.info('2 %j', deep);
12
+ // logger.info('3 \n%j', deep);
13
+ // logger.info('4 %s %s', 1, 2);
14
+ // logger.info('5 %o', deep);
15
+ // logger.info(deep);
16
+ // logger.warn('execed');
17
+ // logger.error(new Error('not found'));
17
18
 
18
- // import { format } from 'logform';
19
+ import { createLogger } from './pino';
20
+ import { genTraceId } from './trace';
19
21
 
20
- // const jsonFormat = format.json({ space: 2 });
21
- // const info = jsonFormat.transform({
22
- // level: 'info',
23
- // message: 'my message',
24
- // });
25
- // console.log(info);
22
+ console.log(genTraceId());
package/src/trace.ts ADDED
@@ -0,0 +1,15 @@
1
+ import { AsyncLocalStorage } from 'async_hooks';
2
+
3
+ const als = new AsyncLocalStorage<{ traceId: string } & any>();
4
+
5
+ export function runInTrace<T>(data: any, fn: (...args: any[]) => T): T {
6
+ return als.run(data, fn);
7
+ }
8
+
9
+ export function genTraceId() {
10
+ return crypto.randomUUID();
11
+ }
12
+
13
+ export function getTraceId() {
14
+ return als.getStore()?.traceId;
15
+ }
package/src/winston.ts ADDED
@@ -0,0 +1,180 @@
1
+ import path from 'path';
2
+ import { AsyncLocalStorage } from 'async_hooks';
3
+
4
+ import chalk from 'chalk';
5
+ import winston from 'winston';
6
+ import JSONStringify from 'safe-stable-stringify';
7
+ import 'winston-daily-rotate-file';
8
+
9
+ import { isDev, isProd } from './env';
10
+ import { getTraceId } from './trace';
11
+
12
+ export type { winston };
13
+
14
+ const levelColor = {
15
+ info: chalk.green,
16
+ error: chalk.redBright,
17
+ warn: chalk.yellow,
18
+ };
19
+
20
+ const levelSymbolMap = {
21
+ info: 'INF',
22
+ warn: 'WRN',
23
+ error: 'ERR',
24
+ };
25
+
26
+ // 设置traceId
27
+ // https://www.npmjs.com/package/cls-rtracer
28
+ const tracerFormat = (options: { writeToFile: boolean; format: { time: boolean } }) =>
29
+ winston.format.printf(info => {
30
+ let traceId = getTraceId();
31
+ const color = (message: string, chalk: chalk.Chalk) => (options.writeToFile ? message : chalk(message));
32
+ const levelit = (text: string) => {
33
+ switch (info.level) {
34
+ case 'info': {
35
+ return color(text, levelColor.info);
36
+ }
37
+ case 'warn': {
38
+ return color(text, levelColor.warn);
39
+ }
40
+ case 'error': {
41
+ return color(text, levelColor.error);
42
+ }
43
+ }
44
+ return text;
45
+ };
46
+ const levelSymbol = levelSymbolMap[info.level as keyof typeof levelSymbolMap];
47
+ const level = levelSymbol ? levelit(` [${levelSymbol}]`) : '';
48
+ const service = info.metadata.service ? levelit(` [${info.metadata.service}]`) : '';
49
+ const timestamp = options.format.time ? color(info.timestamp, chalk.gray) : '';
50
+ const trace = traceId ? color(` [${traceId}]`, chalk.gray) : '';
51
+ let message = info.message || '';
52
+ if (typeof info?.message !== 'string') {
53
+ try {
54
+ if (isDev()) {
55
+ message = '\n' + JSONStringify(info?.message, undefined, 4);
56
+ } else {
57
+ message = JSONStringify(info?.message, undefined, 0);
58
+ }
59
+ } catch (e) {
60
+ message = 'fail to stringify json';
61
+ }
62
+ }
63
+ message = ' ' + message;
64
+ const stack = info.metadata.stack ? color('\n' + info.metadata.stack + '\n', chalk.gray) : '';
65
+ return `${timestamp}${trace}${level}${service}${message}${stack}`;
66
+ });
67
+
68
+ export namespace Logger {
69
+ export interface Options {
70
+ /**
71
+ * 输出日志到console
72
+ * 默认:development环境下输出,production环境下不输出
73
+ */
74
+ writeToConsole?: boolean;
75
+
76
+ /**
77
+ * 输出日志到文件
78
+ * 默认:development环境下输出,production环境下不输出
79
+ */
80
+ writeToFile?: boolean;
81
+
82
+ /**
83
+ * 输出日志的文件目录
84
+ * 默认:./logs/
85
+ */
86
+ dirname?: string;
87
+
88
+ /**
89
+ * 输出日志的文件名
90
+ * 默认:server
91
+ */
92
+ filename?: string;
93
+
94
+ /**
95
+ * 日志输出格式
96
+ */
97
+ format?: {
98
+ /**
99
+ * 显示时间
100
+ * 默认:true
101
+ */
102
+ time?: boolean;
103
+
104
+ /**
105
+ * 显示traceId
106
+ * 默认:true
107
+ */
108
+ traceId?: boolean;
109
+ };
110
+ }
111
+ }
112
+
113
+ export interface Logger {
114
+ info: winston.LeveledLogMethod;
115
+ warn: winston.LeveledLogMethod;
116
+ error: winston.LeveledLogMethod;
117
+ setMetaData: (data: any) => void;
118
+ }
119
+
120
+ export function createLogger(options?: Logger.Options) {
121
+ let transports: winston.transport[] = [];
122
+ let config = {
123
+ writeToConsole: options?.writeToConsole ?? isDev(),
124
+ writeToFile: options?.writeToFile ?? isProd(),
125
+ dirname: options?.dirname || path.join(process.cwd(), './logs/'),
126
+ filename: options?.filename || 'server',
127
+ format: {
128
+ time: options?.format?.time ?? true,
129
+ },
130
+ };
131
+ if (config.writeToFile) {
132
+ transports.push(
133
+ new winston.transports.DailyRotateFile({
134
+ // https://www.npmjs.com/package/winston-daily-rotate-file
135
+ filename: config.filename,
136
+ dirname: config.dirname,
137
+ datePattern: 'YYYY-MM-DD',
138
+ maxFiles: '30d',
139
+ extension: '.log',
140
+ }),
141
+ );
142
+ }
143
+
144
+ if (config.writeToConsole) {
145
+ transports.push(new winston.transports.Console());
146
+ }
147
+
148
+ const { combine, timestamp, colorize, errors, metadata, splat } = winston.format;
149
+ const timeFormat = isProd() ? 'YYYY-MM-DD HH:mm:ss.SSS' : 'HH:mm:ss.SSS';
150
+ let format: winston.Logform.Format[] = [
151
+ errors({ stack: true }),
152
+ metadata(),
153
+ timestamp({ format: timeFormat }),
154
+ splat(), // https://github.com/winstonjs/logform/blob/master/splat.js
155
+ tracerFormat(config),
156
+ ];
157
+ if (!config.writeToFile) {
158
+ format.push(colorize());
159
+ }
160
+ const instance = winston.createLogger({
161
+ format: combine(...format),
162
+ transports,
163
+ });
164
+
165
+ const setMetaData = (data: any) => {
166
+ instance.defaultMeta = {
167
+ ...instance.defaultMeta,
168
+ ...data,
169
+ };
170
+ };
171
+
172
+ const logger: Logger = {
173
+ info: instance.info.bind(instance),
174
+ warn: instance.warn.bind(instance),
175
+ error: instance.error.bind(instance),
176
+ setMetaData,
177
+ };
178
+
179
+ return { logger };
180
+ }
package/tsconfig.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "extends": "@rife/config/tsconfig.json", // 继承 packages 目录下通用配置
3
3
  "compilerOptions": {
4
4
  "outDir": "dist",
5
- "declaration": true,
5
+ "declaration": false,
6
6
  "baseUrl": ".",
7
7
  "paths": {
8
8
  "@/*": ["./src/*"]
package/dist/index.d.ts DELETED
@@ -1,56 +0,0 @@
1
- import winston from 'winston';
2
- import 'winston-daily-rotate-file';
3
- export { winston };
4
- export declare const getNewTraceId: (size?: number | undefined) => string;
5
- export declare function runInTrace<T>(fn: (...args: any[]) => T): T;
6
- export declare function getTraceId(): any;
7
- export declare namespace Rife {
8
- namespace Logger {
9
- interface Options {
10
- /**
11
- * 输出日志到console
12
- * 默认:development环境下输出,production环境下不输出
13
- */
14
- writeToConsole?: boolean;
15
- /**
16
- * 输出日志到文件
17
- * 默认:development环境下输出,production环境下不输出
18
- */
19
- writeToFile?: boolean;
20
- /**
21
- * 输出日志的文件目录
22
- * 默认:./logs/
23
- */
24
- dirname?: string;
25
- /**
26
- * 输出日志的文件名
27
- * 默认:server
28
- */
29
- filename?: string;
30
- /**
31
- * 日志输出格式
32
- */
33
- format?: {
34
- /**
35
- * 显示时间
36
- * 默认:true
37
- */
38
- time?: boolean;
39
- /**
40
- * 显示traceId
41
- * 默认:true
42
- */
43
- traceId?: boolean;
44
- };
45
- }
46
- }
47
- interface Logger {
48
- info: winston.LeveledLogMethod;
49
- warn: winston.LeveledLogMethod;
50
- error: winston.LeveledLogMethod;
51
- }
52
- }
53
- export declare function createLogger(options?: Rife.Logger.Options): {
54
- logger: Rife.Logger;
55
- instance: winston.Logger;
56
- };
package/dist/test.d.ts DELETED
@@ -1 +0,0 @@
1
- export {};