All files / src/utils logger.js

31.82% Statements 7/22
30% Branches 3/10
28.57% Functions 2/7
31.82% Lines 7/22
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        14x                 14x                               14x                                           14x 85x                                   85x       14x  
import { getSelfScope } from './get-self-scope';
 
function noop () {}
 
const fakeLogger = {
  trace: noop,
  debug: noop,
  log: noop,
  warn: noop,
  info: noop,
  error: noop
};
 
let exportedLogger = fakeLogger;
 
// let lastCallTime;
// function formatMsgWithTimeInfo(type, msg) {
//   const now = Date.now();
//   const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';
//   lastCallTime = now;
//   msg = (new Date(now)).toISOString() + ' | [' +  type + '] > ' + msg + ' ( ' + diff + ' ms )';
//   return msg;
// }
 
function formatMsg (type, msg) {
  msg = '[' + type + '] > ' + msg;
  return msg;
}
 
const global = getSelfScope();
 
function consolePrintFn (type) {
  const func = global.console[type];
  if (func) {
    return function (...args) {
      if (args[0]) {
        args[0] = formatMsg(type, args[0]);
      }
 
      func.apply(global.console, args);
    };
  }
  return noop;
}
 
function exportLoggerFunctions (debugConfig, ...functions) {
  functions.forEach(function (type) {
    exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type);
  });
}
 
export var enableLogs = function (debugConfig) {
  Iif (debugConfig === true || typeof debugConfig === 'object') {
    exportLoggerFunctions(debugConfig,
      // Remove out from list here to hard-disable a log-level
      // 'trace',
      'debug',
      'log',
      'info',
      'warn',
      'error'
    );
    // Some browsers don't allow to use bind on console object anyway
    // fallback to default if needed
    try {
      exportedLogger.log();
    } catch (e) {
      exportedLogger = fakeLogger;
    }
  } else {
    exportedLogger = fakeLogger;
  }
};
 
export var logger = exportedLogger;