Skip to content

Instantly share code, notes, and snippets.

@huttj
Created January 15, 2019 03:13
Show Gist options
  • Save huttj/80f2035314931fb65882a487f0335167 to your computer and use it in GitHub Desktop.
Save huttj/80f2035314931fb65882a487f0335167 to your computer and use it in GitHub Desktop.
A simple logger to dump applications logs into a dedicated Slack instance. It’s the poor person’s logging system, but it works!
const https = require('https');
function postToSlack(body) {
return new Promise(function(ok, fail) {
var jsonObject = JSON.stringify(body);
// the post options
var optionspost = {
host: 'hooks.slack.com',
port: 443,
path: '<SLACK URL PATH HERE>',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(jsonObject, 'utf8')
}
};
var req = https.request(optionspost, function (res) {
var resp = '';
res.on('data', function (d) {
resp += d;
});
res.on('end', function() { ok(resp) });
});
req.on('error', fail);
req.write(jsonObject);
req.end();
});
}
const TYPES = exports.TYPES = {
SUCCESS: 'SUCCESS',
ERROR: 'ERROR',
WARNING: 'WARNING',
INFO: 'INFO',
ACCESS_LOG: 'ACCESS_LOG'
};
const ICONS = {
SUCCESS: ':white_check_mark:',
ERROR: ':fire:',
WARNING: ':warning:',
INFO: ':information_source:',
ACCESS_LOG: ':scroll:'
};
const CHANNELS = {
SUCCESS: 'logs',
ERROR: 'errors',
WARNING: 'errors',
INFO: 'logs',
ACCESS_LOG: 'access-logs'
};
function sendMessage({ message, type=TYPES.INFO, username, channel }) {
const payload = {
username: username || ('system_' + type).toLowerCase(),
icon_emoji: ICONS[type] || ICONS.INFO,
text: message,
channel: '#' + (channel || CHANNELS[type])
};
return postToSlack(payload);
}
function log(message) {
return sendMessage({ message });
}
function warn(message) {
return sendMessage({ message, type: TYPES.WARNING });
}
function error(message) {
return sendMessage({ message, type: TYPES.ERROR });
}
function accessLog(message) {
return sendMessage({ message, type: TYPES.ACCESS_LOG });
}
module.exports = {
TYPES,
sendMessage,
accessLog,
log,
warn,
error
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment