all files / lib/plugins/ simple_formatter.js

94.44% Statements 17/18
75% Branches 3/4
100% Functions 2/2
94.44% Lines 17/18
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                                    10× 10× 10× 10×                                                  
'use strict';
 
const colors = require('colors/safe');
const _ = require('lodash');
const raw = require('../raw');
const pp = require('plugin-party');
 
/**
 * SimpleFormatter is generally suitable for most cases. It output with default template `[<%= level %>][<%= pid %>][<%= datetime %>] <%= category %><%= text %>`.
 *
 * * `level` is the level of log method
 * * `pid` is process id of current process
 * * `datetimte` is ISO datetime string
 * * `category` is the categroy of log method
 * * `text` is the output of formatter of log method
 *
 * @class SimpleFormatter
 * @extends Plugin
 */
const Simple = pp.plugin({
  name: 'simple',
  type: 'formatter',
  configure: function (options) {
    this.options = _.extend(this.options, options);
    colors.setTheme(this.options.theme);
    this.template = _.template(this.options.template);
    return this;
  }
}, {
  template: '[<%= level %>][<%= pid %>][<%= datetime %>] <%= category %><%= text %>',
  theme: {
    debug: 'gray',
    info: 'green',
    warn: 'yellow',
    error: 'red',
    'default': 'green'
  }
});
 
const proto = Simple.prototype;
 
proto.fmt = function (level, event) {
  let category = event.category;
  Eif(raw.withColor(event.target)) {
    level = (colors[level] || colors.default)(level.toUpperCase());
    category = raw.renderWithRandomColor(event.category);
  } else {
    level = level.toUpperCase();
  }
  return this.template({
    level: level,
    category: category,
    datetime: event.datetime.toISOString(),
    text: event.raw,
    pid: process.pid
  });
};
 
module.exports = Simple;