@rife/logger 0.0.5-beta.13 → 0.0.5-beta.17
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 +7 -0
- package/dist/index.js +1 -128
- package/dist/pino.js +77 -0
- package/dist/test.js +31 -18
- package/dist/trace.js +15 -0
- package/dist/winston.js +118 -0
- package/package.json +19 -1
- package/src/env.ts +2 -0
- package/src/index.ts +1 -194
- package/src/pino.ts +94 -0
- package/src/test.ts +33 -18
- package/src/trace.ts +16 -0
- package/src/winston.ts +180 -0
- package/dist/index.d.ts +0 -54
- package/dist/test.d.ts +0 -1
- package/dist/trace.d.ts +0 -0
package/dist/env.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.isProd = exports.isDev = void 0;
|
|
4
|
+
const isDev = () => process.env.NODE_ENV === 'development';
|
|
5
|
+
exports.isDev = isDev;
|
|
6
|
+
const isProd = () => process.env.NODE_ENV === 'production';
|
|
7
|
+
exports.isProd = isProd;
|
package/dist/index.js
CHANGED
|
@@ -1,131 +1,4 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.createLogger = exports.getTraceId = exports.runInTrace = exports.getNewTraceId = void 0;
|
|
4
3
|
const tslib_1 = require("tslib");
|
|
5
|
-
|
|
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
|
-
const safe_stable_stringify_1 = tslib_1.__importDefault(require("safe-stable-stringify"));
|
|
11
|
-
require("winston-daily-rotate-file");
|
|
12
|
-
const als = new async_hooks_1.AsyncLocalStorage();
|
|
13
|
-
const isDev = () => process.env.NODE_ENV === 'development';
|
|
14
|
-
const isProd = () => !isDev();
|
|
15
|
-
// https://github.com/CyberAP/nanoid-dictionary/blob/master/src/nolookalikes.js
|
|
16
|
-
exports.getNewTraceId = (0, nanoid_1.customAlphabet)('346789ABCDEFGHJKLMNPQRTUVWXYabcdefghijkmnpqrtwxyz', 5);
|
|
17
|
-
function runInTrace(fn) {
|
|
18
|
-
return als.run({ traceId: (0, exports.getNewTraceId)() }, fn);
|
|
19
|
-
}
|
|
20
|
-
exports.runInTrace = runInTrace;
|
|
21
|
-
function getTraceId() {
|
|
22
|
-
return als.getStore()?.traceId;
|
|
23
|
-
}
|
|
24
|
-
exports.getTraceId = getTraceId;
|
|
25
|
-
const levelColor = {
|
|
26
|
-
info: chalk_1.default.green,
|
|
27
|
-
error: chalk_1.default.redBright,
|
|
28
|
-
warn: chalk_1.default.yellow,
|
|
29
|
-
};
|
|
30
|
-
const levelSymbolMap = {
|
|
31
|
-
info: 'INF',
|
|
32
|
-
warn: 'WRN',
|
|
33
|
-
error: 'ERR',
|
|
34
|
-
};
|
|
35
|
-
// 设置traceId
|
|
36
|
-
// https://www.npmjs.com/package/cls-rtracer
|
|
37
|
-
const tracerFormat = (options) => winston_1.default.format.printf(info => {
|
|
38
|
-
let traceId = getTraceId();
|
|
39
|
-
const color = (message, chalk) => (options.writeToFile ? message : chalk(message));
|
|
40
|
-
const levelit = (text) => {
|
|
41
|
-
switch (info.level) {
|
|
42
|
-
case 'info': {
|
|
43
|
-
return color(text, levelColor.info);
|
|
44
|
-
}
|
|
45
|
-
case 'warn': {
|
|
46
|
-
return color(text, levelColor.warn);
|
|
47
|
-
}
|
|
48
|
-
case 'error': {
|
|
49
|
-
return color(text, levelColor.error);
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
return text;
|
|
53
|
-
};
|
|
54
|
-
const levelSymbol = levelSymbolMap[info.level];
|
|
55
|
-
const level = levelSymbol ? levelit(` [${levelSymbol}]`) : '';
|
|
56
|
-
const service = info.metadata.service ? levelit(` [${info.metadata.service}]`) : '';
|
|
57
|
-
const timestamp = options.format.time ? color(info.timestamp, chalk_1.default.gray) : '';
|
|
58
|
-
const trace = traceId ? color(` [${traceId}]`, chalk_1.default.gray) : '';
|
|
59
|
-
let message = info.message || '';
|
|
60
|
-
if (typeof info?.message !== 'string') {
|
|
61
|
-
try {
|
|
62
|
-
if (isDev()) {
|
|
63
|
-
message = '\n' + (0, safe_stable_stringify_1.default)(info?.message, undefined, 4);
|
|
64
|
-
}
|
|
65
|
-
else {
|
|
66
|
-
message = (0, safe_stable_stringify_1.default)(info?.message, undefined, 0);
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
catch (e) {
|
|
70
|
-
message = 'fail to stringify json';
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
message = ' ' + message;
|
|
74
|
-
const stack = info.metadata.stack ? color('\n' + info.metadata.stack + '\n', chalk_1.default.gray) : '';
|
|
75
|
-
return `${timestamp}${trace}${level}${service}${message}${stack}`;
|
|
76
|
-
});
|
|
77
|
-
function createLogger(options) {
|
|
78
|
-
let transports = [];
|
|
79
|
-
let config = {
|
|
80
|
-
writeToConsole: options?.writeToConsole ?? isDev(),
|
|
81
|
-
writeToFile: options?.writeToFile ?? isProd(),
|
|
82
|
-
dirname: options?.dirname || path_1.default.join(process.cwd(), './logs/'),
|
|
83
|
-
filename: options?.filename || 'server',
|
|
84
|
-
format: {
|
|
85
|
-
time: options?.format?.time ?? true,
|
|
86
|
-
},
|
|
87
|
-
};
|
|
88
|
-
if (config.writeToFile) {
|
|
89
|
-
transports.push(new winston_1.default.transports.DailyRotateFile({
|
|
90
|
-
// https://www.npmjs.com/package/winston-daily-rotate-file
|
|
91
|
-
filename: config.filename,
|
|
92
|
-
dirname: config.dirname,
|
|
93
|
-
datePattern: 'YYYY-MM-DD',
|
|
94
|
-
maxFiles: '30d',
|
|
95
|
-
extension: '.log',
|
|
96
|
-
}));
|
|
97
|
-
}
|
|
98
|
-
if (config.writeToConsole) {
|
|
99
|
-
transports.push(new winston_1.default.transports.Console());
|
|
100
|
-
}
|
|
101
|
-
const { combine, timestamp, colorize, errors, metadata, splat } = winston_1.default.format;
|
|
102
|
-
const timeFormat = isProd() ? 'YYYY-MM-DD HH:mm:ss.SSS' : 'HH:mm:ss.SSS';
|
|
103
|
-
let format = [
|
|
104
|
-
errors({ stack: true }),
|
|
105
|
-
metadata(),
|
|
106
|
-
timestamp({ format: timeFormat }),
|
|
107
|
-
splat(),
|
|
108
|
-
tracerFormat(config),
|
|
109
|
-
];
|
|
110
|
-
if (!config.writeToFile) {
|
|
111
|
-
format.push(colorize());
|
|
112
|
-
}
|
|
113
|
-
const instance = winston_1.default.createLogger({
|
|
114
|
-
format: combine(...format),
|
|
115
|
-
transports,
|
|
116
|
-
});
|
|
117
|
-
const setMetaData = (data) => {
|
|
118
|
-
instance.defaultMeta = {
|
|
119
|
-
...instance.defaultMeta,
|
|
120
|
-
...data,
|
|
121
|
-
};
|
|
122
|
-
};
|
|
123
|
-
const logger = {
|
|
124
|
-
info: instance.info.bind(instance),
|
|
125
|
-
warn: instance.warn.bind(instance),
|
|
126
|
-
error: instance.error.bind(instance),
|
|
127
|
-
setMetaData,
|
|
128
|
-
};
|
|
129
|
-
return { logger };
|
|
130
|
-
}
|
|
131
|
-
exports.createLogger = createLogger;
|
|
4
|
+
tslib_1.__exportStar(require("./trace"), exports);
|
package/dist/pino.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createHttpLogger = exports.createLogger = void 0;
|
|
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 trace_1 = require("./trace");
|
|
8
|
+
const env_1 = require("./env");
|
|
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
|
+
if ((0, env_1.isDev)() || (0, env_1.isProd)()) {
|
|
19
|
+
targets.push({
|
|
20
|
+
level: 'debug',
|
|
21
|
+
target: 'pino/file',
|
|
22
|
+
options: { destination: './.logs/1.log', mkdir: true },
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
const config = {
|
|
26
|
+
base: { pid: undefined, hostname: undefined },
|
|
27
|
+
transport: { targets },
|
|
28
|
+
};
|
|
29
|
+
return config;
|
|
30
|
+
}
|
|
31
|
+
function createLogger(options) {
|
|
32
|
+
let data = {};
|
|
33
|
+
const logger = (0, pino_1.default)({
|
|
34
|
+
...getPinoConfig(),
|
|
35
|
+
mixin() {
|
|
36
|
+
return { traceId: (0, trace_1.getTraceId)(), ...data };
|
|
37
|
+
},
|
|
38
|
+
});
|
|
39
|
+
const setData = (value) => {
|
|
40
|
+
data = { ...data, ...value };
|
|
41
|
+
};
|
|
42
|
+
return {
|
|
43
|
+
info: logger.info.bind(logger),
|
|
44
|
+
warn: logger.warn.bind(logger),
|
|
45
|
+
error: logger.error.bind(logger),
|
|
46
|
+
setData,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
exports.createLogger = createLogger;
|
|
50
|
+
function createHttpLogger() {
|
|
51
|
+
const { pinoHttp } = require('pino-http');
|
|
52
|
+
const logger = pinoHttp({
|
|
53
|
+
...getPinoConfig(),
|
|
54
|
+
mixin() {
|
|
55
|
+
return { traceId: (0, trace_1.getTraceId)() };
|
|
56
|
+
},
|
|
57
|
+
genReqId: trace_1.getTraceId,
|
|
58
|
+
customAttributeKeys: {
|
|
59
|
+
req: 'request',
|
|
60
|
+
res: 'response',
|
|
61
|
+
responseTime: 'duration',
|
|
62
|
+
},
|
|
63
|
+
serializers: {
|
|
64
|
+
req(req) {
|
|
65
|
+
// console.log('==========req.raw.body', req.raw.body);
|
|
66
|
+
req.body = req.raw.body;
|
|
67
|
+
return req;
|
|
68
|
+
},
|
|
69
|
+
res(res) {
|
|
70
|
+
// console.log('==========req.raw.body', res.raw.);
|
|
71
|
+
return res;
|
|
72
|
+
},
|
|
73
|
+
},
|
|
74
|
+
});
|
|
75
|
+
return logger;
|
|
76
|
+
}
|
|
77
|
+
exports.createHttpLogger = createHttpLogger;
|
package/dist/test.js
CHANGED
|
@@ -2,21 +2,34 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
process.env.NODE_ENV = 'development';
|
|
4
4
|
// process.env.NODE_ENV = 'production';
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
const
|
|
8
|
-
|
|
9
|
-
logger.info('
|
|
10
|
-
logger.info('
|
|
11
|
-
logger.info('
|
|
12
|
-
logger.info('
|
|
13
|
-
logger.info(deep);
|
|
14
|
-
logger.
|
|
15
|
-
logger.
|
|
16
|
-
//
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
5
|
+
process.env.NODE_ENV = 'development';
|
|
6
|
+
// import { createLogger } from './winston';
|
|
7
|
+
// const { logger } = createLogger({ writeToFile: false, writeToConsole: true, format: { time: false } });
|
|
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'));
|
|
17
|
+
const pino_1 = require("./pino");
|
|
18
|
+
const trace_1 = require("./trace");
|
|
19
|
+
const logger = (0, pino_1.createLogger)();
|
|
20
|
+
logger.debug({ data: { a: 1 } });
|
|
21
|
+
logger.warn({ data: { a: 2 } });
|
|
22
|
+
const e = new Error('123');
|
|
23
|
+
logger.error(e, '123');
|
|
24
|
+
(0, trace_1.runInTrace)(() => {
|
|
25
|
+
logger.info({ request: { method: 'POST', path: '/123', query: {}, body: {} }, response: 2, data: { a: 1 } }, '请求结束');
|
|
26
|
+
logger.info('123');
|
|
27
|
+
logger.info('123');
|
|
28
|
+
logger.info('123');
|
|
29
|
+
logger.info('123');
|
|
30
|
+
logger.info('123');
|
|
31
|
+
logger.info('123');
|
|
32
|
+
logger.info('123');
|
|
33
|
+
logger.info('123');
|
|
34
|
+
logger.info('123');
|
|
35
|
+
});
|
package/dist/trace.js
CHANGED
|
@@ -1 +1,16 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getTraceId = exports.runInTrace = exports.getNewTraceId = void 0;
|
|
4
|
+
const async_hooks_1 = require("async_hooks");
|
|
5
|
+
const nanoid_1 = require("nanoid");
|
|
6
|
+
const als = new async_hooks_1.AsyncLocalStorage();
|
|
7
|
+
// https://github.com/CyberAP/nanoid-dictionary/blob/master/src/nolookalikes.js
|
|
8
|
+
exports.getNewTraceId = (0, nanoid_1.customAlphabet)('346789ABCDEFGHJKLMNPQRTUVWXYabcdefghijkmnpqrtwxyz', 5);
|
|
9
|
+
function runInTrace(fn) {
|
|
10
|
+
return als.run({ traceId: (0, exports.getNewTraceId)() }, fn);
|
|
11
|
+
}
|
|
12
|
+
exports.runInTrace = runInTrace;
|
|
13
|
+
function getTraceId() {
|
|
14
|
+
return als.getStore()?.traceId;
|
|
15
|
+
}
|
|
16
|
+
exports.getTraceId = getTraceId;
|
package/dist/winston.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createLogger = void 0;
|
|
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
|
+
exports.createLogger = createLogger;
|
package/package.json
CHANGED
|
@@ -1,9 +1,24 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rife/logger",
|
|
3
|
-
"version": "0.0.5-beta.
|
|
3
|
+
"version": "0.0.5-beta.17",
|
|
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
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"typesVersions": {
|
|
16
|
+
"*": {
|
|
17
|
+
"pino": [
|
|
18
|
+
"./src/pino"
|
|
19
|
+
]
|
|
20
|
+
}
|
|
21
|
+
},
|
|
7
22
|
"files": [
|
|
8
23
|
"dist/**/*",
|
|
9
24
|
"src/**/*",
|
|
@@ -12,6 +27,9 @@
|
|
|
12
27
|
"dependencies": {
|
|
13
28
|
"chalk": "4",
|
|
14
29
|
"nanoid": "^3.3.6",
|
|
30
|
+
"pino": "^8.16.1",
|
|
31
|
+
"pino-http": "^8.5.1",
|
|
32
|
+
"pino-pretty": "^10.2.3",
|
|
15
33
|
"safe-stable-stringify": "^2.4.3",
|
|
16
34
|
"winston": "^3.9.0",
|
|
17
35
|
"winston-daily-rotate-file": "^4.7.1",
|
package/src/env.ts
ADDED
package/src/index.ts
CHANGED
|
@@ -1,194 +1 @@
|
|
|
1
|
-
|
|
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 type { 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 Logger {
|
|
83
|
-
export interface Options {
|
|
84
|
-
/**
|
|
85
|
-
* 输出日志到console
|
|
86
|
-
* 默认:development环境下输出,production环境下不输出
|
|
87
|
-
*/
|
|
88
|
-
writeToConsole?: boolean;
|
|
89
|
-
|
|
90
|
-
/**
|
|
91
|
-
* 输出日志到文件
|
|
92
|
-
* 默认:development环境下输出,production环境下不输出
|
|
93
|
-
*/
|
|
94
|
-
writeToFile?: boolean;
|
|
95
|
-
|
|
96
|
-
/**
|
|
97
|
-
* 输出日志的文件目录
|
|
98
|
-
* 默认:./logs/
|
|
99
|
-
*/
|
|
100
|
-
dirname?: string;
|
|
101
|
-
|
|
102
|
-
/**
|
|
103
|
-
* 输出日志的文件名
|
|
104
|
-
* 默认:server
|
|
105
|
-
*/
|
|
106
|
-
filename?: string;
|
|
107
|
-
|
|
108
|
-
/**
|
|
109
|
-
* 日志输出格式
|
|
110
|
-
*/
|
|
111
|
-
format?: {
|
|
112
|
-
/**
|
|
113
|
-
* 显示时间
|
|
114
|
-
* 默认:true
|
|
115
|
-
*/
|
|
116
|
-
time?: boolean;
|
|
117
|
-
|
|
118
|
-
/**
|
|
119
|
-
* 显示traceId
|
|
120
|
-
* 默认:true
|
|
121
|
-
*/
|
|
122
|
-
traceId?: boolean;
|
|
123
|
-
};
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
export interface Logger {
|
|
128
|
-
info: winston.LeveledLogMethod;
|
|
129
|
-
warn: winston.LeveledLogMethod;
|
|
130
|
-
error: winston.LeveledLogMethod;
|
|
131
|
-
setMetaData: (data: any) => void;
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
export function createLogger(options?: Logger.Options) {
|
|
135
|
-
let transports: winston.transport[] = [];
|
|
136
|
-
let config = {
|
|
137
|
-
writeToConsole: options?.writeToConsole ?? isDev(),
|
|
138
|
-
writeToFile: options?.writeToFile ?? isProd(),
|
|
139
|
-
dirname: options?.dirname || path.join(process.cwd(), './logs/'),
|
|
140
|
-
filename: options?.filename || 'server',
|
|
141
|
-
format: {
|
|
142
|
-
time: options?.format?.time ?? true,
|
|
143
|
-
},
|
|
144
|
-
};
|
|
145
|
-
if (config.writeToFile) {
|
|
146
|
-
transports.push(
|
|
147
|
-
new winston.transports.DailyRotateFile({
|
|
148
|
-
// https://www.npmjs.com/package/winston-daily-rotate-file
|
|
149
|
-
filename: config.filename,
|
|
150
|
-
dirname: config.dirname,
|
|
151
|
-
datePattern: 'YYYY-MM-DD',
|
|
152
|
-
maxFiles: '30d',
|
|
153
|
-
extension: '.log',
|
|
154
|
-
}),
|
|
155
|
-
);
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
if (config.writeToConsole) {
|
|
159
|
-
transports.push(new winston.transports.Console());
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
const { combine, timestamp, colorize, errors, metadata, splat } = winston.format;
|
|
163
|
-
const timeFormat = isProd() ? 'YYYY-MM-DD HH:mm:ss.SSS' : 'HH:mm:ss.SSS';
|
|
164
|
-
let format: winston.Logform.Format[] = [
|
|
165
|
-
errors({ stack: true }),
|
|
166
|
-
metadata(),
|
|
167
|
-
timestamp({ format: timeFormat }),
|
|
168
|
-
splat(), // https://github.com/winstonjs/logform/blob/master/splat.js
|
|
169
|
-
tracerFormat(config),
|
|
170
|
-
];
|
|
171
|
-
if (!config.writeToFile) {
|
|
172
|
-
format.push(colorize());
|
|
173
|
-
}
|
|
174
|
-
const instance = winston.createLogger({
|
|
175
|
-
format: combine(...format),
|
|
176
|
-
transports,
|
|
177
|
-
});
|
|
178
|
-
|
|
179
|
-
const setMetaData = (data: any) => {
|
|
180
|
-
instance.defaultMeta = {
|
|
181
|
-
...instance.defaultMeta,
|
|
182
|
-
...data,
|
|
183
|
-
};
|
|
184
|
-
};
|
|
185
|
-
|
|
186
|
-
const logger: Logger = {
|
|
187
|
-
info: instance.info.bind(instance),
|
|
188
|
-
warn: instance.warn.bind(instance),
|
|
189
|
-
error: instance.error.bind(instance),
|
|
190
|
-
setMetaData,
|
|
191
|
-
};
|
|
192
|
-
|
|
193
|
-
return { logger };
|
|
194
|
-
}
|
|
1
|
+
export * from './trace';
|
package/src/pino.ts
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import pino from 'pino';
|
|
2
|
+
// https://github.com/pinojs/pino/blob/master/docs/api.md
|
|
3
|
+
|
|
4
|
+
import { getTraceId } from './trace';
|
|
5
|
+
import { isDev, isProd } from './env';
|
|
6
|
+
|
|
7
|
+
export interface ILogger {
|
|
8
|
+
info: pino.LogFn;
|
|
9
|
+
warn: pino.LogFn;
|
|
10
|
+
error: pino.LogFn;
|
|
11
|
+
setData: (value: any) => any;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export namespace ILogger {
|
|
15
|
+
export interface Options {}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function getPinoConfig() {
|
|
19
|
+
const targets: any = [];
|
|
20
|
+
|
|
21
|
+
if (isDev()) {
|
|
22
|
+
targets.push({
|
|
23
|
+
level: 'debug',
|
|
24
|
+
target: 'pino-pretty', // must be installed separately,
|
|
25
|
+
options: {},
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
if (isDev() || isProd()) {
|
|
30
|
+
targets.push({
|
|
31
|
+
level: 'debug',
|
|
32
|
+
target: 'pino/file',
|
|
33
|
+
options: { destination: './.logs/1.log', mkdir: true },
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
const config: pino.LoggerOptions = {
|
|
37
|
+
base: { pid: undefined, hostname: undefined },
|
|
38
|
+
transport: { targets },
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
return config;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function createLogger(options?: ILogger.Options): ILogger {
|
|
45
|
+
let data: any = {};
|
|
46
|
+
|
|
47
|
+
const logger = pino({
|
|
48
|
+
...getPinoConfig(),
|
|
49
|
+
mixin() {
|
|
50
|
+
return { traceId: getTraceId(), ...data };
|
|
51
|
+
},
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
const setData = (value: any) => {
|
|
55
|
+
data = { ...data, ...value };
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
return {
|
|
59
|
+
info: logger.info.bind(logger),
|
|
60
|
+
warn: logger.warn.bind(logger),
|
|
61
|
+
error: logger.error.bind(logger),
|
|
62
|
+
setData,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function createHttpLogger() {
|
|
67
|
+
const { pinoHttp } = require('pino-http') as typeof import('pino-http');
|
|
68
|
+
|
|
69
|
+
const logger = pinoHttp({
|
|
70
|
+
...getPinoConfig(),
|
|
71
|
+
mixin() {
|
|
72
|
+
return { traceId: getTraceId() };
|
|
73
|
+
},
|
|
74
|
+
genReqId: getTraceId,
|
|
75
|
+
customAttributeKeys: {
|
|
76
|
+
req: 'request',
|
|
77
|
+
res: 'response',
|
|
78
|
+
responseTime: 'duration',
|
|
79
|
+
},
|
|
80
|
+
serializers: {
|
|
81
|
+
req(req) {
|
|
82
|
+
// console.log('==========req.raw.body', req.raw.body);
|
|
83
|
+
req.body = req.raw.body;
|
|
84
|
+
return req;
|
|
85
|
+
},
|
|
86
|
+
res(res) {
|
|
87
|
+
// console.log('==========req.raw.body', res.raw.);
|
|
88
|
+
return res;
|
|
89
|
+
},
|
|
90
|
+
},
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
return logger;
|
|
94
|
+
}
|
package/src/test.ts
CHANGED
|
@@ -1,25 +1,40 @@
|
|
|
1
1
|
process.env.NODE_ENV = 'development';
|
|
2
2
|
// process.env.NODE_ENV = 'production';
|
|
3
|
+
process.env.NODE_ENV = 'development';
|
|
4
|
+
|
|
5
|
+
// import { createLogger } from './winston';
|
|
6
|
+
|
|
7
|
+
// const { logger } = createLogger({ writeToFile: false, writeToConsole: true, format: { time: false } });
|
|
3
8
|
|
|
4
|
-
|
|
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'));
|
|
5
18
|
|
|
6
|
-
|
|
19
|
+
import { createLogger } from './pino';
|
|
20
|
+
import { runInTrace } from './trace';
|
|
7
21
|
|
|
8
|
-
const
|
|
9
|
-
logger.
|
|
10
|
-
logger.
|
|
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'));
|
|
22
|
+
const logger = createLogger();
|
|
23
|
+
logger.debug({ data: { a: 1 } });
|
|
24
|
+
logger.warn({ data: { a: 2 } });
|
|
17
25
|
|
|
18
|
-
|
|
26
|
+
const e = new Error('123');
|
|
27
|
+
logger.error(e, '123');
|
|
19
28
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
29
|
+
runInTrace(() => {
|
|
30
|
+
logger.info({ request: { method: 'POST', path: '/123', query: {}, body: {} }, response: 2, data: { a: 1 } }, '请求结束');
|
|
31
|
+
logger.info('123');
|
|
32
|
+
logger.info('123');
|
|
33
|
+
logger.info('123');
|
|
34
|
+
logger.info('123');
|
|
35
|
+
logger.info('123');
|
|
36
|
+
logger.info('123');
|
|
37
|
+
logger.info('123');
|
|
38
|
+
logger.info('123');
|
|
39
|
+
logger.info('123');
|
|
40
|
+
});
|
package/src/trace.ts
CHANGED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'async_hooks';
|
|
2
|
+
|
|
3
|
+
import { customAlphabet } from 'nanoid';
|
|
4
|
+
|
|
5
|
+
const als = new AsyncLocalStorage<{ traceId: string } & any>();
|
|
6
|
+
|
|
7
|
+
// https://github.com/CyberAP/nanoid-dictionary/blob/master/src/nolookalikes.js
|
|
8
|
+
export const getNewTraceId = customAlphabet('346789ABCDEFGHJKLMNPQRTUVWXYabcdefghijkmnpqrtwxyz', 5);
|
|
9
|
+
|
|
10
|
+
export function runInTrace<T>(fn: (...args: any[]) => T): T {
|
|
11
|
+
return als.run({ traceId: getNewTraceId() }, fn);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function getTraceId() {
|
|
15
|
+
return als.getStore()?.traceId;
|
|
16
|
+
}
|
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/dist/index.d.ts
DELETED
|
@@ -1,54 +0,0 @@
|
|
|
1
|
-
import winston from 'winston';
|
|
2
|
-
import 'winston-daily-rotate-file';
|
|
3
|
-
export type { 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 Logger {
|
|
8
|
-
interface Options {
|
|
9
|
-
/**
|
|
10
|
-
* 输出日志到console
|
|
11
|
-
* 默认:development环境下输出,production环境下不输出
|
|
12
|
-
*/
|
|
13
|
-
writeToConsole?: boolean;
|
|
14
|
-
/**
|
|
15
|
-
* 输出日志到文件
|
|
16
|
-
* 默认:development环境下输出,production环境下不输出
|
|
17
|
-
*/
|
|
18
|
-
writeToFile?: boolean;
|
|
19
|
-
/**
|
|
20
|
-
* 输出日志的文件目录
|
|
21
|
-
* 默认:./logs/
|
|
22
|
-
*/
|
|
23
|
-
dirname?: string;
|
|
24
|
-
/**
|
|
25
|
-
* 输出日志的文件名
|
|
26
|
-
* 默认:server
|
|
27
|
-
*/
|
|
28
|
-
filename?: string;
|
|
29
|
-
/**
|
|
30
|
-
* 日志输出格式
|
|
31
|
-
*/
|
|
32
|
-
format?: {
|
|
33
|
-
/**
|
|
34
|
-
* 显示时间
|
|
35
|
-
* 默认:true
|
|
36
|
-
*/
|
|
37
|
-
time?: boolean;
|
|
38
|
-
/**
|
|
39
|
-
* 显示traceId
|
|
40
|
-
* 默认:true
|
|
41
|
-
*/
|
|
42
|
-
traceId?: boolean;
|
|
43
|
-
};
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
export interface Logger {
|
|
47
|
-
info: winston.LeveledLogMethod;
|
|
48
|
-
warn: winston.LeveledLogMethod;
|
|
49
|
-
error: winston.LeveledLogMethod;
|
|
50
|
-
setMetaData: (data: any) => void;
|
|
51
|
-
}
|
|
52
|
-
export declare function createLogger(options?: Logger.Options): {
|
|
53
|
-
logger: Logger;
|
|
54
|
-
};
|
package/dist/test.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
package/dist/trace.d.ts
DELETED
|
File without changes
|