-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathindex.js
80 lines (63 loc) · 1.83 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
const dgram = require('dgram')
const os = require('os')
const winston = require('winston')
/* eslint-disable no-empty-function */
function noop() {}
/* eslint-enable no-empty-function */
class LogstashTransport extends winston.Transport {
constructor(options) {
options = options || {}
super(options)
this.name = 'LogstashTransport'
this.host = options.host
this.port = options.port
this.trailingLineFeed = options.trailingLineFeed === true
this.trailingLineFeedChar = options.trailingLineFeedChar || os.EOL
this.silent = options.silent
this.client = null
this.connect()
}
connect() {
this.client = dgram.createSocket('udp4')
this.client.unref()
}
log(info, callback) {
if (this.silent) {
return callback(null, true)
}
this.send(info[Symbol.for('message')], (err) => {
this.emit('logged', !err)
callback(err, !err)
})
}
send(message, callback) {
if (this.trailingLineFeed === true) {
message = message.replace(/\s+$/, '') + this.trailingLineFeedChar
}
const buf = Buffer.from(message)
this.client.send(buf, 0, buf.length, this.port, this.host, (callback || noop))
}
}
function createLogger(logType, config) {
const appendMetaInfo = winston.format((info) => {
return Object.assign(info, {
application: logType || config.application,
hostname: config.hostname || os.hostname(),
pid: process.pid,
time: new Date(),
})
})
return winston.createLogger({
level: config.level || 'info',
format: winston.format.combine(
appendMetaInfo(),
winston.format.json(),
winston.format.timestamp()
),
transports: [
new LogstashTransport(config.logstash)
].concat(config.transports || [])
})
}
exports.LogstashTransport = LogstashTransport
exports.createLogger = createLogger