consolereplacer
Version:
Replacer of original console methods.
130 lines (107 loc) • 2.71 kB
JavaScript
/**
* Console Replacer
*
* @version 1.2.2
* @author Maplemx
* @email Maplemx@gmail.com
*/
var fs = require('fs');
function ConsoleReplacer(appName) {
appName = appName ? appName : 'Unamed App';
var separator = '\t',
subtitle = '',
enabled = true,
doLogFile = false;
function formatContent(inputArguments, isDebug) {
var result = new Date().toLocaleString() + separator + //Time
'[' + appName + ']' + separator + //App Name
(subtitle ? subtitle + separator : ''); //Subtitle
if (isDebug) result = '👉👉👉 ' + result;
for (var i = 0; i < inputArguments.length; i++) {
if (typeof(inputArguments[i]) === 'object') {
try {
result += JSON.stringify(inputArguments[i]) + separator;
} catch(e) {
result += inputArguments[i].toString() + separator;
}
} else {
result += typeof(inputArguments[i]) !== 'undefined' ? inputArguments[i].toString() : 'undefined';
result += separator;
}
}
return result;
}
function logContentToFile(contentString) {
var now = new Date();
fs.open(
'./' + appName + '_logs/' + appName + '_' + (1900 + now.getYear()) + '_' + (now.getMonth() + 1) + '_' + now.getDate() + '.log',
'a',
function(e, fd) {
fs.writeSync(fd, contentString + '\n');
fs.close(fd);
}
);
}
function outputLog(consoleMethod, inputArguments, isDebug) {
if (enabled) {
var contentString = formatContent(inputArguments, isDebug);
console[consoleMethod](contentString);
if (doLogFile && !isDebug) {
logContentToFile(contentString);
}
} else {
return false;
}
}
this.log = function() {
outputLog('log', arguments);
}
this.info = function() {
outputLog('info', arguments);
}
this.warn = function() {
outputLog('warn', arguments);
}
this.error = function() {
outputLog('error', arguments);
}
this.trace = function() {
outputLog('trace', arguments);
}
this.debug = function() {
outputLog('log', arguments, true);
}
this.debugTrace = function() {
outputLog('trace', arguments, true);
}
this.setSeparator = function(newSeparator) {
separator = newSeparator;
}
this.setSubtitle = function(newSubtitle) {
subtitle = newSubtitle;
}
this.getSubtitle = function() {
return subtitle;
}
this.setLogFile = function(newDoLogFile) {
doLogFile = newDoLogFile;
if (doLogFile) {
try {
fs.mkdirSync('./' + appName + '_logs');
} catch(e) {
if (e.code !== 'EEXIST') throw e;
}
}
}
this.setEnabled = function(newEnabled) {
enabled = newEnabled;
}
this.setAppName = function(newAppName) {
appName = newAppName;
}
this.classic = console;
return this;
}
module.exports = function(appName){
return new ConsoleReplacer(appName);
}