-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.js
42 lines (36 loc) · 991 Bytes
/
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
const chalk = require('chalk')
const moment = require('moment')
const colours = {
5: 'red',
4: 'yellow',
3: 'cyan',
2: 'green',
1: 'green',
0: 'yellow'
}
const method = ({ method }) => method
const url = ({ originalUrl }) => originalUrl
const remoteAddress = ({ request }) => request.ip
const duration = (start) => () => `- ${new Date() - start} ms`
const time = () => moment().format('YYYY-MM-DD[T]HH:mm:ss.SSSZZ')
const status = ({ status }) => chalk[colours[status / 100 | 0] || 'reset'](status)
const httpVersion = ({ req }) => `HTTP/${req.httpVersionMajor}.${req.httpVersionMinor}`
function log (ctx, start) {
const tokens = [
time,
method,
httpVersion,
status,
remoteAddress,
url,
duration(start)
]
console.log(tokens.map(x => x(ctx)).join(' '))
}
module.exports = () => async (ctx, next) => {
const start = new Date()
await next()
ctx.res
.once('close', () => log(ctx, start))
.once('finish', () => log(ctx, start))
}