-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathaccessLogger.js
More file actions
executable file
·66 lines (53 loc) · 1.66 KB
/
Copy pathaccessLogger.js
File metadata and controls
executable file
·66 lines (53 loc) · 1.66 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
'use strict';
// adapted koa-logger for bunyan
// binds onfinish to current context
// bindEmitter didn't work here
exports.init = function(app) {
app.use(async function logger(ctx, next) {
// request
let req = ctx.req;
let start = Date.now();
ctx.log.info({
event: "request-start",
method: req.method,
url: req.url,
referer: ctx.request.get('referer'),
ua: ctx.request.get('user-agent')
}, "--> %s %s", req.method, req.originalUrl || req.url);
try {
await next();
} catch (err) {
// log uncaught downstream errors
log(ctx, start, err);
throw err;
}
// log when the response is finished or closed,
// whichever happens first.
let res = ctx.res;
let onfinish = done.bind(null, 'finish');
let onclose = done.bind(null, 'close');
function done(event) {
res.removeListener('finish', onfinish);
res.removeListener('close', onclose);
log(ctx, start, null, event);
}
/**
* Log helper.
*/
function log(ctx, start, err, event) {
// get the status code of the response
let status = err ? (err.status || 500) : (ctx.status || 404);
// set the color of the status code;
let s = status / 100 | 0;
// not ctx.url, but ctx.originalUrl because mount middleware changes it
// request to /payments/common/order in case of error is logged as /order
ctx.log[err ? 'error' : 'info']({
event: "request-end",
method: ctx.method,
url: ctx.originalUrl,
status: status,
timeDuration: Date.now() - start
}, "<-- %s %s", ctx.method, ctx.originalUrl);
}
});
};