All files / piscosour/lib logger.js

21.69% Statements 18/83
13.95% Branches 6/43
15.79% Functions 3/19
21.69% Lines 18/83
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 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189    1x 1x 1x 1x 1x   1x                     1x               1x                                                           1x     177x 1x 1x 1x     177x                                                                                                                                                                       156x         2x         19x                                                     1x  
'use strict';
 
const moment = require('moment');
const params = require('./params');
const fs = require('fs');
const path = require('path');
const chalk = require('chalk');
 
const levels = {
  silly: 5,
  debug: 4,
  verbose: 3,
  info: 2,
  warning: 1,
  error: 0,
  default: 2
};
let gLevel;
 
const countIt = function(args){
  let n = 0;
  args.forEach((arg) => {
    n += arg.startsWith('#') ? 2: arg.length;
  });
  return n;
};
 
const repeatIt = function(char, n) {
  let res = char;
  for (let i = 0; i < n-1; i++) {
    res += char;
  }
  return res;
};
 
/**
 * Generate logger wrapper to be use inside a Step.
 *
 * There are 6 levels:
 *
 * 5. silly,
 * 4. debug,
 * 3. verbose,
 * 2. info,
 * 1. warning,
 * 0. error
 *
 * Formating messages is possible with chalk tags...
 *
 * Example of use inside step
 *
 * ```
 * this.logger.info('#green','text');
 * ```
 *
 * @module logger
 */
const logger = {
 
  getLevel() {
    if (gLevel === undefined){
      gLevel = levels[params.output];
      Eif (!gLevel) {
        gLevel = levels.default;
      }
    }
    return gLevel;
  },
 
  setLevel(level) {
    gLevel = level;
  },
 
  isLevel: function(name) {
    return logger.getLevel() >= levels[name];
  },
 
  //TODO: concatenar estilos de chalk red + bold (etc..)
  prettyPrint: function() {
    const args = Array.prototype.slice.call(arguments);
    const initArg = args[0];
    const res = [ '[' + chalk.grey(moment().format('HH:mm:ss')) + ']' ];
    let color;
    for (const con in initArg) {
      if (initArg.hasOwnProperty(con)) {
        let item = initArg[con];
        if (item && typeof item === 'string' && item.charAt(0) === '#') {
          color = item.replace('#', '');
        } else {
          if (color) {
            if (color === 'duration') {
              item = chalk.cyan(moment.utc(item).format(logger.duration(item)));
            } else if (chalk[color]) {
              item = chalk[color](item);
            }
            color = null;
          }
          res.push(item);
        }
      }
    }
    return res;
  },
  duration: function(milis) {
    let pattern = 'SSS [ms]';
    if (milis >= 1000 && milis < 60000) {
      pattern = 'ss [s] SSS [ms]';
    } else if (milis >= 60000 && milis < 3600000) {
      pattern = 'mm [m] ss [s] SSS [ms]';
    } else if (milis >= 3600000) {
      pattern = 'hh [h] mm [m] ss [s] SSS [ms]';
    }
    return pattern;
  },
  out: function() {
    process.stdout.write.apply(process.stdout, arguments);
  },
  err: function() {
    process.stderr.write.apply(process.stderr, arguments);
  },
  txt: function() {
    console.log.apply(this, arguments);
  },
  traceError: function() {
    console.trace.apply(this, this.prettyPrint(arguments));
  },
  error: function() {
    console.error.apply(this, this.prettyPrint(arguments));
  },
  warn: function() {
    if (logger.getLevel() >= 1) {
      console.info.apply(this, this.prettyPrint(arguments));
    }
  },
  framed: function() {
    if (logger.getLevel() >= 2) {
      const args = Array.prototype.slice.call(arguments);
      const count = countIt(args);
      let res = ['\n\n', '#cyan', repeatIt('*', (count/2) - 1), '#green', 'READ THIS', '#cyan', repeatIt('*', (count/2) - 1), '\n\n', '   '];
      res = res.concat(args);
      res.push('\n\n', '#cyan', repeatIt('*', count+10 < 13 ? 13 : count+10),'\n');
      console.info.apply(this, this.prettyPrint(res));
    }
  },
  info: function() {
    if (logger.getLevel() >= 2) {
      console.info.apply(this, this.prettyPrint(arguments));
    }
  },
  trace: function() {
    Iif (logger.getLevel() >= 3) {
      console.info.apply(this, this.prettyPrint(arguments));
    }
  },
  debug: function() {
    Iif (logger.getLevel() >= 4) {
      console.info.apply(this, this.prettyPrint(arguments));
    }
  },
  silly: function() {
    Iif (logger.getLevel() >= 5) {
      console.info.apply(this, this.prettyPrint(arguments));
    }
  },
  parseMd: function() {
    var marked = require('marked');
    var TerminalRenderer = require('marked-terminal');
 
    marked.setOptions({
      renderer: new TerminalRenderer()
    });
    const args = Array.prototype.slice.call(arguments);
    let txt = '';
    args.forEach((file) => {
      let buffer;
      try {
        buffer = fs.readFileSync(file);
        txt = buffer.toString();
        return;
      } catch (e) {
        this.trace('Error reading', file, e);
      }
    });
    this.txt(marked(txt));
  }
};
 
module.exports = logger;