xpl / ololog

A better console.log for the log-driven debugging junkies
https://www.npmjs.com/package/ololog
The Unlicense
215 stars 8 forks source link

Feature request: severity #12

Open ourarash opened 5 years ago

ourarash commented 5 years ago

I was able to hack a severity level so that a message only prints if its severity is above the min severity level. This is useful when for example you run the program in a verbose vs non-verbose mode.

Here is what worked for me:

const bullet = require("string.bullet");
const { cyan, yellow, red, dim, blue } = require("ansicolor");

var log = require("ololog").configure({
  locate: false,
  infoSeverity: 5,
  tag: (
    lines,
    {
      level = "",
      minSeverity=10,
      severity = 11,
      levelColor = {
        info: cyan,
        warn: yellow,
        error: red.bright.inverse,
        debug: blue
      }
    }
  ) => {
    const levelStr =
      level && (levelColor[level] || (s => s))(level.toUpperCase());
    if (severity >= minSeverity) {
      return bullet(levelStr.padStart(6) + "  ", lines);
    } else return [];
  }
});

log("This prints!");

log
.configure({tag:{severity:12}})
.info("This will print, severity 12!");

log
.configure({tag:{severity:1}})
.info("This will print, severity 1!");

log
.configure({tag:{severity:15}})
.info("This will print, severity 15!");

log = log
.configure({tag:{minSeverity:1000}}); // change severity

log
.configure({tag:{severity:12}})
.info("This will not print, severity 12!");

log
.configure({tag:{severity:1}})
.info("This will not print, severity 1!");

log
.configure({tag:{severity:15}})
.info("This will not print, severity 15!");

However, this is ugly. Ideally, it should be like this:

var log = require("ololog").configure({
  locate: false,
  infoMinSeverity: 5,
  warnMinSeverity: 6,
  debugMinSeverity: 8,
  errorMinSeverity: 10,
  minSeverity: 15, //without tag
});

log.severity(5).info('This is my message');
log.configure({infoMinSeverity:0}).info('This is my message');
xpl commented 5 years ago

@ourarash Have you looked into this: https://github.com/xpl/ololog#adding-custom-helper-methods ?

Try that code:

log = require ('ololog')
        .configure (/* YOUR CONFIG HERE */)
        .methods ({
            severity (n) { return this.configure ({ tag: { severity: n } }) })
        })

This will allow you to do this:

log.severity(5).info('This is my message')