UNPKG

aono-file-handler

Version:

Aono handler that write to a log file with support for custom formatters and log rotation.

55 lines 1.96 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.LogstashFormatter = void 0; /** * @author Maciej Chałapuk (maciej@chalapuk.pl) */ class LogstashFormatter { constructor(prefix = 'data_', consts = {}) { this.prefix = prefix; this.consts = consts; } format(entry) { const date = new Date(); date.setTime(entry.timestamp); const formattedDate = date.toISOString(); const message = '{ ' + `"timestamp": ${safeJsonStringify(formattedDate)}, ` + `"logger": ${safeJsonStringify(entry.logger)}, ` + `"level": ${safeJsonStringify(entry.level)}, ` + `"message": ${safeJsonStringify(entry.message)}` + Object.keys(this.consts) .map(key => `, "${key}": ${safeJsonStringify(this.consts[key])}`) .join('') + Object.keys(entry.data) .map(key => `, "${this.prefix}${key}": ${safeJsonStringify(entry.data[key])}`) .join('') + ' }\n'; const utfEncoded = encodeUtf(message); return utfEncoded; } } exports.LogstashFormatter = LogstashFormatter; exports.default = LogstashFormatter; function safeJsonStringify(obj) { try { if (obj instanceof Error && obj.stack) { // Errors are stringified to arrays containing stack trace // which will render nicely in Kibana. return JSON.stringify(obj.stack.split('\n')); } else { return JSON.stringify(obj); } } catch (e) { return `["### Error while stringifying object of type ${typeof obj} ###","${e.message}"]`; } } function encodeUtf(message) { return message.replace(/[\u00A0-\u9999<>\&]/gim, i => { const hex = i.charCodeAt(0).toString(16); return `\\u${(hex.length === 2 ? '00' : '')}${hex}`; }); } //# sourceMappingURL=LogstashFormatter.js.map