aboutsummaryrefslogtreecommitdiff
path: root/lib/loggers/console.js
blob: 5e5ded1241d494ac0bcfcb70cf23cdff34ead9f0 (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
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
'use strict';

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

/**
 * Logger for the javascript console.
 *
 * @implements ILogger
 * @memberof Loggers
 * @class Console
 */
module.exports = class ConsoleLogger {
  constructor(config) {

    /**
     * The console it will write to, can be any object that looks
     * and acts like a console, including other cologne objects.
     *
     * @name console
     * @instance
     * @memberof Loggers.Console
     * @type Object
     * @default global.console
     */
    this.console = console;

    /**
     * The formatter it will use to output the log. If not present it
     * will output raw JSON
     *
     * @name formatter
     * @instance
     * @memberof Loggers.Console
     * @type IFormatter
     * @default null
     */
    this.formatter = null;

    Object.assign(this, config);
  }


  /**
   * Main entry point, for each incoming argument it will attempt to
   * format and send to the console.
   *
   * @function log
   * @instance
   * @memberof Loggers.Console
   * @return {undefined}
   */
  log(...logs) {

    const formattedLogs = logs.map((log) => ({ log: this._format(log), level: log._level }));

    for (const { log, level } of formattedLogs) {
      this._log(log, level );
    }

  }

  // Routes an individual log to the appropriatet console

  _log(log, level) {

    switch (level) {
    case 0:
    case 1:
    case 2:
    case 3:
      this.console.error(log);
      break;
    case 4:
      this.console.warn(log);
      break;
    case 5:
    case 6:
      this.console.info(log);
      break;
    case 7:
    default:
      this.console.log(log);
      break;
    }
  }

  _format(logObject) {

    if (this.formatter) {
      return this.formatter.format(logObject);
    }

    return Utilities.stringify(logObject);
  }
};