]> git.r.bdr.sh - rbdr/cologne/blob - lib/cologne/formatter/token.js
bb905ca260ed853fef0f521c6450c357e51303fa
[rbdr/cologne] / lib / cologne / formatter / token.js
1 'use strict';
2
3 let LogUtilities = require('../log_utilities');
4
5 /**
6 * Token formatter. Given a format string it will attempt to output
7 * a message.
8 *
9 * @memberof Cologne.Formatter
10 * @implements Cologne.IFormatter
11 * @class Token
12 */
13 let TokenFormatter = class TokenFormatter {
14 constructor (config) {
15
16 /**
17 * The string to use as a template string. By default, any property
18 * inside double curly braces `{{likeThis}}` will be extracted from
19 * the object and replaced. If the object does not contain the
20 * property, it will leave it.
21 *
22 * @name formatString
23 * @instance
24 * @memberof Cologne.Formatter.Token
25 * @type String
26 * @default '{{message}}'
27 */
28 this.formatString = '{{message}}';
29
30 /**
31 * The regex rule to use to match the tokens.
32 *
33 * @name replaceRule
34 * @instance
35 * @memberof Cologne.Formatter.Token
36 * @type RegExp
37 * @default /{{(.*)}}/g
38 */
39 this.replaceRule = /{{(.*?)}}/g;
40
41 /**
42 * Flag that specifies whether or not to use an isoDate when using
43 * `_timestamp`. If false it will output the raw timestamp.
44 *
45 * @name isoDate
46 * @instance
47 * @memberof Cologne.Formatter.Token
48 * @type Boolean
49 * @default true
50 */
51 this.isoDate = true;
52
53 this._ansiRe = /_ansi:.+/;
54
55 Object.assign(this, config || {});
56 }
57
58 /**
59 * Main entry point, it will read the incoming log object and convert
60 * all the tokens to their corresponding representation, finally
61 * returning the string.
62 *
63 * @function format
64 * @instance
65 * @memberof Cologne.Formatter.Token
66 * @param {Cologne.tCologneLog} logObjet the log to format
67 * @return {String} the formatted object
68 */
69 format (logObject) {
70 let resultString, escapeCode;
71
72 escapeCode = String.fromCharCode(27);
73
74 resultString = this.formatString.replace(this.replaceRule, function (match, token) {
75 let date, ansiType;
76
77 if (token === '_timestamp' && this.isoDate) {
78 date = new Date(logObject._timestamp);
79 return date.toISOString();
80 }
81
82 if (token.match(this._ansiRe)) {
83 ansiType = token.split(':')[1];
84
85 // Smartish coloring
86 if (ansiType === '_level') {
87 return escapeCode + LogUtilities.getAnsiCode(LogUtilities.getLevelAnsi(logObject._level));
88 }
89
90 return escapeCode + LogUtilities.getAnsiCode(ansiType);
91 }
92
93 if (!logObject.hasOwnProperty(token)) {
94 return match;
95 }
96
97 return logObject[token];
98 }.bind(this));
99
100 return resultString;
101 }
102 };
103
104 module.exports = TokenFormatter;