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