-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlogger.js
55 lines (48 loc) · 1.28 KB
/
logger.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
const morgan = require('morgan');
const fs = require('fs');
function colorForStatus(status) {
if (status >= 500) {
return 31; // red
}
if (status >= 400) {
return 33; // yellow
}
if (status >= 300) {
return 36; // cyan
}
if (status >= 200) {
return 32; // green
}
return 0; // no color
}
morgan.format('dev+', function developmentFormatLine(tokens, req, res) {
// eslint-disable-next-line
'use strict';
// get the status code if response written
// eslint-disable-next-line no-underscore-dangle
const status = res._header
? res.statusCode
: undefined;
// get status color
const color = colorForStatus(status);
// get colored function
let fn = developmentFormatLine[color];
if (!fn) {
// compile
// eslint-disable-next-line
fn = developmentFormatLine[color] = morgan.compile('\x1b[0m:method :url \x1b['
+ color + 'm:status \x1b[0m:response-time ms - :res[content-length]\x1b[0m ' +
':req[x-request-id]');
}
return fn(tokens, req, res);
});
module.exports.init = (env) => {
if (env === 'test') {
return morgan('tiny', {
stream: fs.createWriteStream(`${__dirname}/logs/test.log`, { flags: 'w' }),
});
} else if (env === 'production') {
return morgan('combined');
}
return morgan('dev+');
};