]> git.r.bdr.sh - rbdr/cologne/blob - lib/cologne/formatter/simple.js
48821fc597e1f1b12bc86c6f39e800dfd5ff327b
[rbdr/cologne] / lib / cologne / formatter / simple.js
1 'use strict';
2
3 let LogUtilities = require('../log_utilities');
4
5 /**
6 * Simple formatter. Outputs a predefined format:
7 * `[{{_timestamp}}][{{_levelString}}] {{_from}}: {{message}}`;
8 *
9 * @memberof Cologne.Formatter
10 * @implements Cologne.IFormatter
11 * @class Simple
12 */
13 let SimpleFormatter = class SimpleFormatter {
14
15 constructor (config) {
16
17 /**
18 * Flag that tells us whether or not to use ANSI color. Defaults to
19 * false.
20 *
21 * @name colorize
22 * @instance
23 * @memberof Cologne.Formatter.Simple
24 * @type Boolean
25 * @default false
26 */
27 this.colorize = false;
28
29 Object.assign(this, config || {});
30 }
31
32 /**
33 * Main entry point, it will read the incoming log object and convert
34 * it to the output string.
35 *
36 * @function format
37 * @instance
38 * @memberof Cologne.Formatter.Simple
39 * @param {Cologne.tCologneLog} logObjet the log to format
40 * @return {String} the formatted object
41 */
42 format (logObject) {
43 let date, levelString;
44
45 date = new Date(logObject._timestamp);
46 date = date.toISOString();
47 levelString = this._colorize(logObject._levelString, logObject._level);
48
49 return `[${date}][${levelString}] ${logObject._from}: ${logObject.message}`;
50 }
51
52 _colorize (levelString, level) {
53 let escapeCode, color, reset;
54
55 if (!this.colorize) {
56 return levelString;
57 }
58
59 escapeCode = String.fromCharCode(27);
60 color = escapeCode + LogUtilities.getAnsiCode(LogUtilities.getLevelAnsi(level));
61 reset = escapeCode + LogUtilities.getAnsiCode('reset');
62
63 return color + levelString + reset;
64 }
65 };
66
67 module.exports = SimpleFormatter;