-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
105 lines (88 loc) · 2.18 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
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
93
94
95
96
97
98
99
100
101
102
103
104
105
'use strict'
var pino = require('pino')
function logging (opts) {
opts = opts || {}
opts.stream = opts.stream || process.stdout
var logger = pino(opts.pinoOptions || {}, opts.stream)
var instance = opts.instance
var servers = opts.servers
if (!servers) {
if (opts.server) {
servers = [opts.server]
} else {
servers = []
}
}
instance.logger = logger
servers.forEach(function (server) {
server.on('listening', function () {
var address = server.address()
if (server.key && server.cert && server.hasOwnProperty('httpAllowHalfOpen')) {
address.protocol = 'https'
} else if (server.key && server.cert) {
address.protocol = 'tls'
} else if (server.hasOwnProperty('httpAllowHalfOpen')) {
address.protocol = 'http'
} else {
address.protocol = 'tcp'
}
logger.info(address, 'listening')
})
})
instance.on('client', function (client) {
client.logger = logger.child({
client: {
id: client.id
}
})
client.logger.info('connected')
})
instance.on('clientDisconnect', function (client) {
if (client.logger) {
client.logger.info('disconnected')
} else {
logger.warn('disconnect without connect')
}
})
instance.on('subscribe', function (subscriptions, client) {
client.logger.info({
subscriptions: subscriptions
}, 'subscribed')
})
instance.on('unsubscribe', function (subscriptions, client) {
client.logger.info({
topics: subscriptions
}, 'unsubscribed')
})
instance.on('clientError', function (client, err) {
if (client.logger) {
client.logger.warn(err)
} else {
logger.warn({
client: client,
err: err
}, err.message)
}
})
// default is true
if (opts.messages !== false) {
instance.on('publish', logPublish)
}
return instance
}
function logPublish (publish, client) {
var logger = this.logger
var level = 'debug'
if (client) {
level = 'info'
logger = client.logger
}
logger[level]({
message: {
topic: publish.topic,
qos: publish.qos,
retain: publish.retain
}
}, 'published')
}
module.exports = logging