Skip to content

Commit 71420cd

Browse files
author
pedro
committed
feat:添加自定义的日志类
1 parent c1de5b1 commit 71420cd

6 files changed

Lines changed: 128 additions & 17 deletions

File tree

example/logger.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
const Logger = require('egg-logger').Logger;
2-
const ConsoleTransport = require('egg-logger').ConsoleTransport;
32

43
const { FileTransport } = require('../lin/logger/file');
4+
const { ConsoleTransport } = require('../lin/logger/console');
55

66
const logger = new Logger();
77
logger.set(
88
'file',
99
new FileTransport({
1010
dir: 'log',
1111
sizeLimit: 1024 * 5,
12-
level: 'INFO'
12+
level: 'DEBUG'
1313
})
1414
);
1515
logger.set(
@@ -25,8 +25,8 @@ logger.info('info foo');
2525
// for (let i = 0; i < 1000; i++) {}
2626

2727
setInterval(() => {
28-
logger.info('loop');
28+
logger.info('we will never be slavers!!!');
2929
}, 100);
3030

3131
logger.warn('warn foo');
32-
logger.error(new Error('error foo'));
32+
// logger.error(new Error('error foo'));

lib/core.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ export class Lin {
9797
const pluginRp = new LinRouter({ prefix: '/plugin' });
9898
Object.values(this.manager!.plugins).forEach(plugin => {
9999
consola.info(`loading plugin: ${get(plugin, 'name')}`);
100-
const controllers = Object.values(get(plugin, 'controllers'));
100+
const controllers: any[] = Object.values(get(plugin, 'controllers'));
101101
if (controllers.length > 1) {
102102
controllers.forEach(cont => {
103103
set(
@@ -117,8 +117,8 @@ export class Lin {
117117
set(ly, 'path', `/${get(plugin, 'name')}${get(ly, 'path')}`);
118118
});
119119
pluginRp
120-
.use((cont as any).routes() as IMiddleware)
121-
.use((cont as any).allowedMethods() as IMiddleware);
120+
.use(cont.routes() as IMiddleware)
121+
.use(cont.allowedMethods() as IMiddleware);
122122
});
123123
} else {
124124
controllers.forEach(cont => {
@@ -128,8 +128,8 @@ export class Lin {
128128
});
129129
}
130130
pluginRp
131-
.use((cont as any).routes() as IMiddleware)
132-
.use((cont as any).allowedMethods() as IMiddleware);
131+
.use(cont.routes() as IMiddleware)
132+
.use(cont.allowedMethods() as IMiddleware);
133133
});
134134
}
135135
});

lib/extend.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@ export const success = (app: Application) => {
9696
* @param app app实例
9797
*/
9898
export const logging = (app: Application) => {
99+
// TODO: 提供配置项
99100
// const logger = new Logger();
100101
// logger.set(
101102
// 'file',

lib/logger/console.ts

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
'use strict';
2+
3+
import { Transport } from 'egg-logger';
4+
const utils = require('egg-logger/lib/utils');
5+
const levels = require('egg-logger/lib/level');
6+
7+
import { consoleFormatter } from './format';
8+
9+
/**
10+
* output log to console {@link Transport}。
11+
* specifical level by EGG_LOG has the highest priority
12+
*/
13+
export class ConsoleTransport extends Transport {
14+
options: any;
15+
16+
/**
17+
* @constructor
18+
* @param {Object} options
19+
* - {Array} [stderrLevel = ERROR] - output to stderr level, must higher than options.level
20+
*/
21+
constructor(options) {
22+
super(options);
23+
this.options.stderrLevel = utils.normalizeLevel(this.options.stderrLevel);
24+
// EGG_LOG has the highest priority
25+
if (process.env.EGG_LOG) {
26+
this.options.level = utils.normalizeLevel(process.env.EGG_LOG);
27+
}
28+
}
29+
30+
get defaults() {
31+
// @ts-ignore
32+
return utils.assign(super.defaults, {
33+
stderrLevel: 'ERROR'
34+
});
35+
}
36+
37+
/**
38+
* output log, see {@link Transport#log}
39+
* if stderrLevel presents, will output log to stderr
40+
* @param {String} level - log level, in upper case
41+
* @param {Array} args - all arguments
42+
* @param {Object} meta - meta infomations
43+
*/
44+
log(level, args, meta) {
45+
meta = meta || {};
46+
meta.formatter = consoleFormatter;
47+
const msg: any = super.log(level, args, meta);
48+
if (
49+
levels[level] >= this.options.stderrLevel &&
50+
levels[level] < levels['NONE']
51+
) {
52+
process.stderr.write(msg);
53+
} else {
54+
process.stdout.write(msg);
55+
}
56+
}
57+
}

lib/logger/file.ts

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,15 @@ const depd = require('depd')('egg-logger');
1111
const utils = require('egg-logger/lib/utils');
1212

1313
import { Transport } from 'egg-logger';
14+
import { consoleFormatter } from './format';
1415

1516
/**
1617
* output log into file {@link Transport}。
1718
*/
1819
export class FileTransport extends Transport {
1920
_stream: fs.WriteStream | null;
2021
options: any;
21-
logCount: number = 1;
22+
2223
/**
2324
* @constructor
2425
* @param {Object} options
@@ -31,7 +32,6 @@ export class FileTransport extends Transport {
3132
assert(this.options.sizeLimit, 'should pass options.sizeLimit');
3233

3334
this._stream = null;
34-
this.logCount = 1;
3535
this.reload();
3636
}
3737

@@ -65,13 +65,13 @@ export class FileTransport extends Transport {
6565
// 存在,则判断是否溢出
6666
if (filename) {
6767
const overflow = this.checkSizeOverflow(filename);
68-
// 如果溢出,logCount ++ , reload
68+
// 如果溢出,reload
6969
if (overflow) {
70-
this.logCount += 1;
70+
// filename重命名
71+
this.renameLogFile(filename);
7172
this.reload();
7273
}
7374
} else {
74-
this.logCount = 1;
7575
this.reload();
7676
}
7777

@@ -80,19 +80,33 @@ export class FileTransport extends Transport {
8080
console.error(err.stack);
8181
return;
8282
}
83+
meta = meta || {};
84+
meta.formatter = consoleFormatter;
8385
const buf = super.log(level, args, meta);
8486
// @ts-ignore
8587
if (buf.length) {
8688
this._write(buf);
8789
}
8890
}
8991

92+
renameLogFile(filename: string) {
93+
const today = dayjs();
94+
const dir = path.dirname(filename);
95+
const mill = today.format('HH:mm:ss');
96+
const refilename = path.join(
97+
dir,
98+
`${today.format('YYYY-MM-DD')}-${mill}.log`
99+
);
100+
fs.renameSync(filename, refilename);
101+
}
102+
90103
/**
91104
* 检查当前的日志文件是否为当天
92105
*/
93106
checkIsPresent() {
94107
// 检查前面的日志
95-
// 2019-05-29.1.log
108+
// 2019-06-01-21:29:01.log
109+
// 而且检查当前文件夹
96110
const filename = this.getPresentFilename();
97111
const exist = fs.existsSync(filename);
98112
if (exist) {
@@ -106,8 +120,10 @@ export class FileTransport extends Transport {
106120
const dir: string = path.isAbsolute(this.options.dir)
107121
? this.options.dir
108122
: path.join(process.cwd(), this.options.dir);
109-
const today = dayjs().format('YYYY-MM-DD');
110-
const filename = path.join(dir, `${today}.${this.logCount}.log`);
123+
const today = dayjs();
124+
const ddir = path.join(dir, today.format('YYYY-MM'));
125+
const dfilename = today.format('YYYY-MM-DD');
126+
const filename = path.join(ddir, `${dfilename}.log`);
111127
return filename;
112128
}
113129

lib/logger/format.ts

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
const chalk = require('chalk');
2+
const os = require('os');
3+
4+
const hostname = os.hostname();
5+
const duartionRegexp = /([0-9]+ms)/g;
6+
// eslint-disable-next-line no-useless-escape
7+
const categoryRegexp = /(\[[\w\-_.:]+\])/g;
8+
const httpMethodRegexp = /(GET|POST|PUT|PATH|HEAD|DELETE) /g;
9+
10+
// output to Terminal format
11+
export function consoleFormatter(meta) {
12+
let msg =
13+
meta.date +
14+
' ' +
15+
meta.level +
16+
' ' +
17+
meta.pid +
18+
' ' +
19+
' --- ' +
20+
`[${hostname}]` +
21+
' - ' +
22+
meta.message;
23+
if (!chalk.supportsColor) {
24+
return msg;
25+
}
26+
27+
if (meta.level === 'ERROR') {
28+
return chalk.red(msg);
29+
} else if (meta.level === 'WARN') {
30+
return chalk.yellow(msg);
31+
}
32+
33+
// msg = msg.replace(duartionRegexp, chalk.green('$1'));
34+
// msg = msg.replace(categoryRegexp, chalk.blue('$1'));
35+
// msg = msg.replace(httpMethodRegexp, chalk.cyan('$1 '));
36+
return msg;
37+
}

0 commit comments

Comments
 (0)