forked from fahad19/winston-slack-hook
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
76 lines (60 loc) · 1.66 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
var util = require('util');
var request = require('request');
var winston = require('winston');
var SlackHook = winston.transports.SlackHook = function (options) {
this.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 || true;
this.appendMeta = options.appendMeta || true;
this.formatter = options.formatter || null;
};
util.inherits(SlackHook, winston.Transport);
SlackHook.prototype.log = function (level, msg, meta, callback) {
var message = '';
if (this.prependLevel === true) {
message += '[' + level + '] ';
}
message += msg;
if (
this.appendMeta === true &&
meta &&
Object.getOwnPropertyNames(meta).length
) {
message += ' ```' + JSON.stringify(meta, null, 2) + '```';
}
if (typeof this.formatter === 'function') {
message = this.formatter({
level: level,
message: message,
meta: meta
});
}
var payload = {
channel: this.channel,
username: this.username,
text: message
};
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);
});
};
module.exports = SlackHook;