]> git.r.bdr.sh - rbdr/cologne/blame - lib/formatters/token.js
Cache the nyc_output dir
[rbdr/cologne] / lib / formatters / token.js
CommitLineData
58906d77
RBR
1'use strict';
2
ae85c067 3const Utilities = require('../utilities');
58906d77
RBR
4
5/**
6 * Token formatter. Given a format string it will attempt to output
7 * a message.
8 *
ae85c067
RBR
9 * @memberof Formatters
10 * @implements IFormatter
58906d77
RBR
11 * @class Token
12 */
ae85c067
RBR
13module.exports = class TokenFormatter {
14 constructor(config) {
58906d77
RBR
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
ae85c067 24 * @memberof Formatters.Token
58906d77
RBR
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
ae85c067 35 * @memberof Formatters.Token
58906d77
RBR
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
ae85c067 47 * @memberof Formatters.Token
58906d77
RBR
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
ae85c067
RBR
65 * @memberof Formatters.Token
66 * @param {tCologneLog} log the log to format
58906d77
RBR
67 * @return {String} the formatted object
68 */
ae85c067 69 format(log) {
58906d77 70
ae85c067
RBR
71 const escapeCode = String.fromCharCode(27);
72 return this.formatString.replace(this.replaceRule, (match, token) => {
58906d77
RBR
73
74 if (token === '_timestamp' && this.isoDate) {
ae85c067 75 const date = new Date(Number(log._timestamp) / 1000000);
58906d77
RBR
76 return date.toISOString();
77 }
78
79 if (token.match(this._ansiRe)) {
ae85c067 80 const ansiType = token.split(':')[1];
58906d77
RBR
81
82 // Smartish coloring
83 if (ansiType === '_level') {
ae85c067 84 return escapeCode + Utilities.getAnsiCode(Utilities.getLevelAnsi(log._level));
58906d77
RBR
85 }
86
ae85c067 87 return escapeCode + Utilities.getAnsiCode(ansiType);
58906d77
RBR
88 }
89
ae85c067
RBR
90 return log[token] || match;
91 });
58906d77
RBR
92 }
93};