Skip to content

Instantly share code, notes, and snippets.

@gnitnuj
Created August 27, 2020 13:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gnitnuj/b7faf81423cf2c32e65e9e56317b81a6 to your computer and use it in GitHub Desktop.
Save gnitnuj/b7faf81423cf2c32e65e9e56317b81a6 to your computer and use it in GitHub Desktop.
module.exports = {
/**
* Create a logger
* @param {string} prefix
* @param {object] options
* - indent (number of spaces to indent)
*/
create(prefix, options = {}) {
if (typeof options.indent === 'undefined') {
options.indent = 0;
}
let totalIndent = '';
if (options.indent !== 0) {
totalIndent += Array.apply(null, Array(options.indent))
.map(() => {
return ' ';
})
.join('');
}
return function(data, options = {}) {
let indent = totalIndent;
if (typeof options.indent === 'undefined') {
options.indent = 0;
}
if (options.indent !== 0) {
indent += Array.apply(null, Array(options.indent))
.map(() => {
return ' ';
})
.join('');
}
if (typeof data === 'object') {
data = JSON.stringify(data, null, 2);
}
data = data.replace(/(\r?\n)/g, `$1${indent} `);
console.log(`${indent}${getTimestamp()}: ${prefix}: ${data}`);
};
},
// logOutErrBuffer
// Takes a logger and uses it to log stdin/stdout data that comes from
// child_process.spawn
// @param {function} log - the log method to call
// @returns {function} callback - the callback to pass to child_process.spawn
logOutErrBuffer(log = console.log) {
return function(data) {
if (data.stdout) {
log(data.stdout);
}
if (data.stderr) {
log(data.stderr);
}
};
},
};
/**
* getTimeStamp
* @param {date}
* @returns {string} timestamp
*/
const getTimestamp = (function() {
const pad = (num) => {
return num > 9 ? num : `0${num}`;
};
return function(d) {
if (!d) {
d = new Date();
}
return [
`${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`,
`${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(
d.getSeconds(),
)}`,
].join(' ');
};
})();
// this file exists just to name the gist, and because gist ordering is asciibetical, it's name starts with a capital letter.
{
"name": "logger",
"version": "0.1.0"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment