-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
62 lines (50 loc) · 1.22 KB
/
index.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
56
57
58
59
60
61
62
const fp = require('fastify-plugin')
const style = require('ansi-styles')
const dateFormat = require('./datetime')
const defaultOptions = {
allInOne: false,
time: true,
timeFormat: 'HH:mm:ss',
level: 1,
info: '#ffffff',
warn: '#ffa500',
error: '#dc143c'
}
function plugin (fastify, opts, next) {
const options = Object.assign(defaultOptions, opts)
function info (...args) {
if (options.level > 1) return
log('info', args)
}
function warn (...args) {
if (options.level > 2) return
log('warn', args)
}
function error (...args) {
if (options.level > 3) return
log('error', args)
}
function log (type, content) {
const time = options.time ? dateFormat(Date.now(), options.timeFormat) + ' ' : ''
const text = content.map(c => typeof c === 'object'
? JSON.stringify(c)
: c).join(' ')
console.log(`${style.color.ansi16m.hex(options[type])}${time}${text}${style.color.close}`)
}
const logger = {
info,
warn,
error
}
if (options.allInOne) {
fastify.decorate('logger', logger)
} else {
Object.keys(logger).forEach(k => {
fastify.decorate(k, logger[k])
})
}
next()
}
module.exports = fp(plugin, {
name: 'fastify-logger'
})