@rife/logger 0.0.5-beta.2 → 0.0.5-beta.4
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/package.json +2 -2
- package/src/index.ts +187 -187
- package/src/test.ts +25 -25
- package/tsconfig.json +12 -12
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rife/logger",
|
|
3
|
-
"version": "0.0.5-beta.
|
|
3
|
+
"version": "0.0.5-beta.4",
|
|
4
4
|
"description": "",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./src/index.ts",
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
"nanoid": "^3.1.30",
|
|
15
15
|
"winston": "^3.3.3",
|
|
16
16
|
"winston-daily-rotate-file": "^4.5.5",
|
|
17
|
-
"@rife/config": "0.0.5-beta.
|
|
17
|
+
"@rife/config": "0.0.5-beta.4"
|
|
18
18
|
},
|
|
19
19
|
"scripts": {
|
|
20
20
|
"dev": "infra dev",
|
package/src/index.ts
CHANGED
|
@@ -1,187 +1,187 @@
|
|
|
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
|
+
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
|
+
}
|
package/src/test.ts
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
|
-
process.env.NODE_ENV = 'development';
|
|
2
|
-
// process.env.NODE_ENV = 'production';
|
|
3
|
-
|
|
4
|
-
import { createLogger } from '.';
|
|
5
|
-
|
|
6
|
-
const { logger } = createLogger({ writeToFile: false, writeToConsole: true, format: { time: false } });
|
|
7
|
-
|
|
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
|
-
|
|
18
|
-
// import { format } from 'logform';
|
|
19
|
-
|
|
20
|
-
// const jsonFormat = format.json({ space: 2 });
|
|
21
|
-
// const info = jsonFormat.transform({
|
|
22
|
-
// level: 'info',
|
|
23
|
-
// message: 'my message',
|
|
24
|
-
// });
|
|
25
|
-
// console.log(info);
|
|
1
|
+
process.env.NODE_ENV = 'development';
|
|
2
|
+
// process.env.NODE_ENV = 'production';
|
|
3
|
+
|
|
4
|
+
import { createLogger } from '.';
|
|
5
|
+
|
|
6
|
+
const { logger } = createLogger({ writeToFile: false, writeToConsole: true, format: { time: false } });
|
|
7
|
+
|
|
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
|
+
|
|
18
|
+
// import { format } from 'logform';
|
|
19
|
+
|
|
20
|
+
// const jsonFormat = format.json({ space: 2 });
|
|
21
|
+
// const info = jsonFormat.transform({
|
|
22
|
+
// level: 'info',
|
|
23
|
+
// message: 'my message',
|
|
24
|
+
// });
|
|
25
|
+
// console.log(info);
|
package/tsconfig.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
{
|
|
2
|
-
"extends": "@rife/config/tsconfig.json", // 继承 packages 目录下通用配置
|
|
3
|
-
"compilerOptions": {
|
|
4
|
-
"outDir": "dist",
|
|
5
|
-
"declaration": true,
|
|
6
|
-
"baseUrl": ".",
|
|
7
|
-
"paths": {
|
|
8
|
-
"@/*": ["./src/*"]
|
|
9
|
-
}
|
|
10
|
-
},
|
|
11
|
-
"include": ["./src/**/*"]
|
|
12
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"extends": "@rife/config/tsconfig.json", // 继承 packages 目录下通用配置
|
|
3
|
+
"compilerOptions": {
|
|
4
|
+
"outDir": "dist",
|
|
5
|
+
"declaration": true,
|
|
6
|
+
"baseUrl": ".",
|
|
7
|
+
"paths": {
|
|
8
|
+
"@/*": ["./src/*"]
|
|
9
|
+
}
|
|
10
|
+
},
|
|
11
|
+
"include": ["./src/**/*"]
|
|
12
|
+
}
|