aboutsummaryrefslogtreecommitdiff
path: root/lib/formatters/simple.js
blob: bfaa76c7dd068d9a28783e82917e473281e01dc6 (plain)
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
'use strict';

const Utilities = require('../utilities');

/**
 * Simple formatter. Outputs a predefined format:
 * `[{{_timestamp}}][{{_levelString}}] {{_from}}: {{message}}`;
 *
 * @memberof Formatters
 * @implements IFormatter
 * @class Simple
 */
module.exports = class SimpleFormatter {

  constructor(config) {

    /**
     * Flag that tells us whether or not to use ANSI color. Defaults to
     * false.
     *
     * @name colorize
     * @instance
     * @memberof Formatters.Simple
     * @type Boolean
     * @default false
     */
    this.colorize = false;

    Object.assign(this, config || {});
  }

  /**
   * Main entry point, it will read the incoming log object and convert
   * it to the output string.
   *
   * @function format
   * @instance
   * @memberof Formatters.Simple
   * @param {tCologneLog} logObjet the log to format
   * @return {String} the formatted object
   */
  format(logObject) {

    const date = (new Date(Number(logObject._timestamp) / 1000000)).toISOString();
    const levelString = this._colorize(logObject._levelString, logObject._level);

    return `[${date}][${levelString}] ${logObject._from}: ${logObject.message}`;
  }

  _colorize(levelString, level) {

    if (!this.colorize) {
      return levelString;
    }

    const escapeCode = String.fromCharCode(27);
    const color = escapeCode + Utilities.getAnsiCode(Utilities.getLevelAnsi(level));
    const reset = escapeCode + Utilities.getAnsiCode('reset');

    return color + levelString + reset;
  }
};