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