@perfectsoft/winston-3-slack-transport
v1.0.0
Published
A demo package for transport slackhook
Downloads
5
Readme
export class SlackTransport extends Transport { constructor(options) { super(options); // // Consume any custom options here. e.g.: // - Connection information for databases // - Authentication information for APIs (e.g. loggly, papertrail, // logentries, etc.). // this.name = options.name || 'slackHook'; this.level = options.level || 'info';
this.username = options.username || 'bot';
this.hookUrl = options.hookUrl || null;
this.channel = options.channel || '#logs';
this.iconEmoji = options.iconEmoji || null;
this.prependLevel = options.prependLevel === undefined ? true : options.prependLevel;
this.appendMeta = options.appendMeta === undefined ? true : options.appendMeta;
this.formatter = options.formatter || null;
this.colors = options.colors || {};
}
log(info, callback) {
callback = function () {};
setImmediate(() => {
this.emit('logged', info);
});
// Perform the writing to the remote service
let message = '';
const level = info.level;
const msg = info.message;
let meta = JSON.parse(JSON.stringify(info));
delete meta.level;
delete meta.message;
if (this.prependLevel && !this.colors[level]) {
message += '[' + level + '] ';
}
message += msg;
if (typeof this.formatter === 'function') {
message = this.formatter({
level,
message,
meta
});
}
let payload = {
channel: this.channel,
username: this.username,
text: message
};
if (
this.appendMeta &&
meta &&
Object.getOwnPropertyNames(meta).length
) {
let fields = [];
for (let key in meta) {
fields.push({
title: key,
value: meta[key]
});
}
payload.attachments = [{
fields
}];
if (this.colors[level]) {
payload.attachments[0].color = this.colors[level];
}
}
if (this.iconEmoji) {
payload.icon_emoji = this.iconEmoji; // jshint ignore:line
}
request
.post(this.hookUrl)
.form({
payload: JSON.stringify(payload)
})
.on('response', function (response) {
if (response.statusCode === 200) {
callback(null, true);
return;
}
callback('Server responded with ' + response.statusCode);
})
.on('error', function (error) {
callback(error);
});
}
}
winston.transports.Slack = SlackTransport;