rabbit-logger
Version:
logging data in RabbitMQ
125 lines (99 loc) • 3.52 kB
JavaScript
const amqp = require(`amqp-connection-manager`)
const moment = require(`moment-timezone`)
module.exports.RabbitLogger = class ClickhouseRabbit {
constructor(config) {
this.config = config
this.config.protocol = this.config.protocol || `amqp`
this.config.timezone = this.config.timezone || `Asia/Almaty`
this.validation()
if (this.msg) {
console.log(this.msg)
return
}
this.connection = amqp.connect({
protocol: this.config.protocol,
hostname: this.config.hostname,
port: this.config.port,
username: this.config.username,
password: this.config.password,
vhost: this.config.vhost,
})
this.connection.on(`connect`, function() {
console.log(`Connected rabbit (ClickHouse Logger).`)
})
this.connection.on(`disconnect`, function(err) {
console.log(`Disconnected rabbit (ClickHouse Logger).`, err)
})
this.send = this.connection.createChannel({
json: true,
setup: function(channel) {
return channel.assertQueue(config.queue, {durable: true})
}
})
}
validation () {
this.msg = ``
if (!this.config.hostname) {
this.msg = `you did not specify a hostname`
}
if (!this.config.port) {
this.msg = `you did not specify a port`
}
if (!this.config.username) {
this.msg = `you did not specify a username`
}
if (!this.config.password) {
this.msg = `you did not specify a password`
}
if (!this.config.vhost) {
this.msg = `you did not specify a vhost`
}
if (!this.config.queue) {
this.msg = `you did not specify a queue`
}
if (!this.config.projectName) {
this.msg = `you did not specify a projectName`
}
}
async sentToQueue(logLevel, data) {
if (this.msg) {
console.log(this.msg)
return
}
let outData = {}
Object.keys(data).forEach(item => {
if ((!!data[item]) && (data[item].constructor === Object)) {
outData[item] = JSON.stringify(data[item])
} else if ((!!data[item]) && (data[item].constructor === Array)) {
outData[item] = JSON.stringify(data[item])
} else {
outData[item] = String(data[item])
}
})
const defaultConf = {
date: moment().tz(this.config.timezone).format(`YYYY-MM-DD`),
dateTime: moment().tz(this.config.timezone).format(`YYYY-MM-DD HH:mm:ss`),
timestamp: Date.now(),
environment: this.config.env || this.config.environment || `dev`,
projectName: this.config.projectName,
requestId: this.config.requestId || ``,
logLevel
}
this.send.sendToQueue(this.config.queue, {
...defaultConf,
...outData
})
}
info(data) {
this.sentToQueue(`INFO`, data)
}
error(data) {
this.sentToQueue(`ERROR`, data)
}
warning(data) {
this.sentToQueue(`WARNING`, data)
}
debug(data) {
this.sentToQueue(`DEBUG`, data)
}
}