Skip to content

Commit

Permalink
bug fixes, don't use console.log by default, improved support in edge…
Browse files Browse the repository at this point in the history
… cases, improve tests
  • Loading branch information
ori-sh committed Aug 27, 2017
1 parent a5a3147 commit a16fca7
Show file tree
Hide file tree
Showing 11 changed files with 148 additions and 107 deletions.
3 changes: 3 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
tests
.gitignore
package-lock.json
10 changes: 0 additions & 10 deletions logs-conf.json

This file was deleted.

89 changes: 48 additions & 41 deletions logs-js.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@ const d = require('print-colors').fg.d;
const l = require('print-colors').fg.l;
const bg = require('print-colors').bg;
const e = require('print-colors').e;
const b = '\033[1m';
const b = '\033[1m'; //Bold
const levelLength = 5;
const fileLength = 24;
const oldLog = console.log;
Error.stackTraceLimit = Infinity;

class LogLevel {
constructor (level, color, name) {
Expand All @@ -21,29 +25,13 @@ const logLevels = {
FATAL: new LogLevel( 6, bg.d.red+l.white, 'FATAL'),
OFF: new LogLevel( 7, '', 'OFF')
}
for (var name in logLevels) {
if (logLevels.hasOwnProperty(name)) {
exports[name] = logLevels[name]
}
}
for (var name in logLevels) { exports[name] = logLevels[name] }

const levelLength = 5;
const fileLength = 24;
let defaultLogLevel;
let conf = {
let conf = { // Default configuration
"*": "ALL"
};

exports.loadConfig = (confFile) => {
let config = require(confFile);
if (config.log && typeof config.log === 'object') {
conf = config.log;
}
if (logLevels[config.defaultLogLevel] && logLevels[config.defaultLogLevel] instanceof LogLevel) {
defaultLogLevel = logLevels[config.defaultLogLevel];
}
}

let findFileLogLevel = (parentLevel, filePathArray, conf) => {
if (conf['*'] && typeof conf['*'] === "string" && logLevels[conf['*']] && logLevels[conf['*']] instanceof LogLevel) {
parentLevel = logLevels[conf['*']];
Expand All @@ -61,39 +49,58 @@ let findFileLogLevel = (parentLevel, filePathArray, conf) => {
}

let printIfAllowed = (logLevel, argumentsArray) => {
let stackLine = new Error().stack.split('\n')[3];
let location = stackLine.substring(stackLine.lastIndexOf('(') + 1, stackLine.length).replace(__dirname + '\\' , '').split(":");
let stackLines = new Error().stack.split('\n');
let reg = /^(.*\\logs-js\.js:[0-9]+:[0-9]+\).*|Error)$/;
let stackLine;
while (reg.test(stackLine = stackLines.shift())) { }
let location = stackLine.substring(stackLine.lastIndexOf('(') + 1, stackLine.length).replace(require.main.filename.substring(0, require.main.filename.lastIndexOf('\\')) + '\\' , '').split(":");
let file = location[0];
let path = file.split('\\', );
let allowedLogLevel = findFileLogLevel(logLevels.OFF, path, conf);

let allowedLogLevel = findFileLogLevel(logLevels.OFF, file.split('\\'), conf);
if (allowedLogLevel.level !== 7 && allowedLogLevel.level <= logLevel.level && logLevel.level != 7) {
let line = location[1];
argumentsArray[0] = l.gray+'['+e+logLevel.color+pad(logLevel.name, levelLength)+e+l.gray+'] - '+e+
d.cyan+new Date().toISOString().replace(/T/, ' ').replace(/Z.*$/, '').replace(/-/g, d.yellow+'-'+d.cyan).replace(/:/g, d.yellow+':'+d.cyan).replace('.', d.yellow+'.'+d.cyan)+e+
l.gray+' - ['+e+pad(file+':',fileLength-(''+line).length).replace('.',d.yellow+'.'+e)+d.cyan+line+e+l.gray+']: '+e+argumentsArray[0];
let print = l.gray+'['+e+logLevel.color+pad(logLevel.name, levelLength)+e+l.gray+'] - '+e+
new Date().toISOString().replace(/T/, ' ').replace(/Z.*$/, '').replace(/-/g, d.red+'-'+e).replace(/:/g, d.red+':'+e).replace('.', d.red+'.'+e+d.cyan)+e+
l.gray+' - ['+e+d.red+'/'+e+file.replace('.',d.red+'.'+e).replace(/\\/g,d.red+'/'+e)+d.red+':'+e+d.cyan+line+e+l.gray+']:'+e+l.white;
if (argumentsArray.length > 0) {
argumentsArray[0] = print + ' ' + argumentsArray[0];
} else {
argumentsArray.unshift(print)
}
oldLog.apply(null, argumentsArray);
}
}

let oldLog = console.log;
console.log = function(){
if ((arguments.length > 0 && arguments[arguments.length - 1] instanceof LogLevel)) {
let logLevel = Array.prototype.pop.apply(arguments);
printIfAllowed(logLevel, arguments);
} else if (defaultLogLevel) {
printIfAllowed(defaultLogLevel, arguments);
} else {
oldLog.apply(null, arguments);
}
}

function pad(str, length) {
let pad = (str, length) => {
let pad = Array(length + 1).join(' ');
if (typeof str === 'undefined')
return pad;
//return (pad + str).slice(-pad.length - 1);
return (str + pad).substring(0, pad.length);
}

let log = exports.log = (...args) => {
if ((args.length > 0 && args[args.length - 1] instanceof LogLevel)) {
printIfAllowed(args.pop(), args);
} else if (defaultLogLevel) {
printIfAllowed(defaultLogLevel, args);
} else {
oldLog.apply(null, args);
}
};
exports.trace = (...args) => { log.apply(null, args.concat(logLevels.TRACE)); };
exports.debug = (...args) => { log.apply(null, args.concat(logLevels.DEBUG)); };
exports.info = (...args) => { log.apply(null, args.concat(logLevels.INFO)); };
exports.warn = (...args) => { log.apply(null, args.concat(logLevels.WARN)); };
exports.error = (...args) => { log.apply(null, args.concat(logLevels.ERROR)); };
exports.fatal = (...args) => { log.apply(null, args.concat(logLevels.FATAL)); };

exports.loadConfig = (config) => {
if (config.log && typeof config.log === 'object') {
conf = config.log;
}
if (logLevels[config.defaultLogLevel] && logLevels[config.defaultLogLevel] instanceof LogLevel) {
defaultLogLevel = logLevels[config.defaultLogLevel];
}
if (config.useConsoleLog && config.useConsoleLog===true) {
console.log = log;
}
}
1 change: 0 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
{
"name": "logs-js",
"version": "1.0.2",
"version": "1.0.4",
"description": "simple JavaScript logging library",
"repository": {
"type": "git",
"url": "https://github.com/ori-shalom/logs-js.git"
},
"main": "logs-js.js",
"scripts": {
"test": "node test.js"
"test": "cd tests && npm pack ../ && npm install --prefix ./ logs-js-1.0.4.tgz && rm logs-js-1.0.4.tgz && node test.js"
},
"author": "Ori Shalom",
"license": "ISC",
Expand Down
44 changes: 0 additions & 44 deletions test.js

This file was deleted.

9 changes: 0 additions & 9 deletions test/test2.js

This file was deleted.

9 changes: 9 additions & 0 deletions tests/directory/nested_directory/test3.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const logsJs = require('logs-js');

logsJs.log('test3 regular logging with no log level');
logsJs.log('test3 TRACE', logsJs.TRACE);
logsJs.log('test3 DEBUG', logsJs.DEBUG);
logsJs.log('test3 INFO', logsJs.INFO);
logsJs.log('test3 WARN', logsJs.WARN);
logsJs.log('test3 ERROR', logsJs.ERROR);
logsJs.log('test3 FATAL', logsJs.FATAL);
9 changes: 9 additions & 0 deletions tests/directory/test2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const logsJs = require('logs-js');

logsJs.log('test2 regular logging with no log level');
logsJs.log('test2 TRACE', logsJs.TRACE);
logsJs.log('test2 DEBUG', logsJs.DEBUG);
logsJs.log('test2 INFO', logsJs.INFO);
logsJs.log('test2 WARN', logsJs.WARN);
logsJs.log('test2 ERROR', logsJs.ERROR);
logsJs.log('test2 FATAL', logsJs.FATAL);
14 changes: 14 additions & 0 deletions tests/logs-conf.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"defaultLogLevel": "INFO",
"useConsoleLog": true,
"log" : {
"*": "ALL",
"test.js": "ALL",
"directory": {
"*": "WARN",
"nested_directory": {
"test3.js": "DEBUG"
}
}
}
}
63 changes: 63 additions & 0 deletions tests/test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
const logsJs = require('logs-js');
logsJs.loadConfig(require('./logs-conf.json'));

require('./directory/test2.js');
require('./directory/nested_directory/test3.js');

console.time('test console.time');
console.timeEnd('test console.time');

console.log('%s def', 'abc');
console.log();
logsJs.trace();
logsJs.trace('test TRACE with trace() function');
logsJs.debug('test DEBUG with debug() function');
logsJs.info('test INFO with info() function');
logsJs.warn('test WARN with warn() function');
logsJs.error('test ERROR with error() function');
logsJs.fatal('test FATAL with fatal() function');
logsJs.log('test TRACE with log() function', logsJs.TRACE);
logsJs.log('test DEBUG with log() function', logsJs.DEBUG);
logsJs.log('test INFO with log() function', logsJs.INFO);
logsJs.log('test WARN with log() function', logsJs.WARN);
logsJs.log('test ERROR with log() function', logsJs.ERROR);
logsJs.log('test FATAL with log() function', logsJs.FATAL);


console.log('test regular logging with console.log() and no log level');
console.log('test TRACE with console.log() function', logsJs.TRACE);
console.log('test DEBUG with console.log() function', logsJs.DEBUG);
console.log('test INFO with console.log() function', logsJs.INFO);
console.log('test WARN with console.log() function', logsJs.WARN);
console.log('test ERROR with console.log() function', logsJs.ERROR);
console.log('test FATAL with console.log() function', logsJs.FATAL);

console.log('called from the root scope', logsJs.INFO);
console.log('called with multiple arguments', 'abc', 'def', 0, 1, 2, logsJs.INFO);
console.log({}, logsJs.INFO);
console.log(JSON.stringify({"msg":"object with some text printted with JSON.stringify()"},null,2), logsJs.INFO);
console.log([{}, 'abc', 3], logsJs.INFO);
(() => {
console.log('called from anonymous function', logsJs.INFO);
})();

let c = () => {
console.log('called from function c', logsJs.INFO);
}

function a(arg) {
console.log(arg, logsJs.INFO);

let b = () => {
console.log('called from function b', logsJs.INFO);
}
b();
c();
}
a('called from function a');
new a('called from constructor function a');

setTimeout(() => {
console.log('called from timeout', logsJs.INFO);
}, 1000);

0 comments on commit a16fca7

Please sign in to comment.