]> git.r.bdr.sh - rbdr/cologne/blob - lib/loggers/console.js
116b04be195342823d745f7039d472f997244adb
[rbdr/cologne] / lib / loggers / console.js
1 'use strict';
2
3 const Utilities = require('../utilities');
4
5 /**
6 * Logger for the javascript console.
7 *
8 * @implements ILogger
9 * @class Console
10 */
11 module.exports = class ConsoleLogger {
12 constructor(config) {
13
14 /**
15 * The console it will write to, can be any object that looks
16 * and acts like a console, including other cologne objects.
17 *
18 * @name console
19 * @instance
20 * @memberof Loggers.Console
21 * @type Object
22 * @default global.console
23 */
24 this.console = console;
25
26 /**
27 * The formatter it will use to output the log. If not present it
28 * will output raw JSON
29 *
30 * @name formatter
31 * @instance
32 * @memberof Loggers.Console
33 * @type IFormatter
34 * @default null
35 */
36 this.formatter = null;
37
38 Object.assign(this, config);
39 }
40
41
42 /**
43 * Main entry point, for each incoming argument it will attempt to
44 * format and send to the console.
45 *
46 * @function log
47 * @instance
48 * @memberof Loggers.Console
49 * @return {undefined}
50 */
51 log(...logs) {
52
53 const formattedLogs = logs.map((log) => ({ log: this._format(log), level: log._level }));
54
55 for (const { log, level } of formattedLogs) {
56 this._log(log, level );
57 }
58
59 }
60
61 // Routes an individual log to the appropriatet console
62
63 _log(log, level) {
64
65 switch (level) {
66 case 0:
67 case 1:
68 case 2:
69 case 3:
70 this.console.error(log);
71 break;
72 case 4:
73 this.console.warn(log);
74 break;
75 case 5:
76 case 6:
77 this.console.info(log);
78 break;
79 case 7:
80 default:
81 this.console.log(log);
82 break;
83 }
84 }
85
86 _format(logObject) {
87
88 if (this.formatter) {
89 return this.formatter.format(logObject);
90 }
91
92 return Utilities.stringify(logObject);
93 }
94 };