-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogging.js
More file actions
93 lines (78 loc) · 2.29 KB
/
logging.js
File metadata and controls
93 lines (78 loc) · 2.29 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const co = require('co');
const uuid = require('uuid');
const chalk = require('chalk');
const bunyan = require('bunyan');
chalk.enabled = true;
let log = bunyan.createLogger({name: 'webhooked'});
let reqresLogger = bunyan.createLogger({
name: 'webhooked',
serializers: {
req: function req(req) {
if (!req || !req.connection) {
return req;
}
let headers = Object.assign({}, req.headers);
delete headers.authentication;
return {
method: req.method,
url: req.url,
headers: headers,
remoteAddress: req.connection.remoteAddress,
remotePort: req.connection.remotePort
};
},
res: bunyan.stdSerializers.res,
err: bunyan.stdSerializers.err
}
});
const methods = [
'log',
'info',
'warn',
'error',
'debug',
'trace'
];
log.log = log.info;
methods.forEach((method)=>{
console[method] = log[method].bind(log);
});
let devLogger = co.wrap(function* (ctx, next){
const start = process.hrtime();
ctx.log = reqresLogger.child({req_id: uuid.v4()});
yield next();
const status = ctx.res.statusCode;
const method = status >= 500 ? chalk.red
: status >= 400 ? chalk.yellow
: status >= 300 ? chalk.cyan
: status >= 200 ? chalk.green
: (str) => str;
const diff = process.hrtime(start);
const res_time = (diff[0] * 1e3 + diff[1] * 1e-6).toFixed(3);
let msg = [
chalk.reset(ctx.req.method),
ctx.req.url,
method(status),
`${res_time}ms -`,
ctx.res._headers['content-length']
].join(' ');
console.log(msg);
});
let prodLogger = co.wrap(function* (ctx, next) {
const start = process.hrtime();
ctx.log = reqresLogger.child({req_id: uuid.v4()});
yield next();
const status = ctx.res.statusCode;
const method = status >= 500 ? 'error'
: status >= 400 ? 'warn'
: 'info';
const diff = process.hrtime(start);
const res_time = (diff[0] * 1e3 + diff[1] * 1e-6).toFixed(3);
ctx.log[method]({req: ctx.req, res: ctx.res, duration: res_time});
});
console.reqLogger = (env) => {
if(env === 'production') {
return prodLogger;
}
return devLogger;
};