|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +/** |
| 4 | + * logstashHTTP appender sends JSON formatted log events to logstashHTTP receivers. |
| 5 | + */ |
| 6 | +const util = require('util'); |
| 7 | +const axios = require('axios'); |
| 8 | + |
| 9 | +function wrapErrorsWithInspect(items) { |
| 10 | + return items.map((item) => { |
| 11 | + if ((item instanceof Error) && item.stack) { |
| 12 | + return { |
| 13 | + inspect: function () { |
| 14 | + return `${util.format(item)}\n${item.stack}`; |
| 15 | + } |
| 16 | + }; |
| 17 | + } |
| 18 | + |
| 19 | + return item; |
| 20 | + }); |
| 21 | +} |
| 22 | + |
| 23 | +function format(logData) { |
| 24 | + const data = Array.isArray(logData) |
| 25 | + ? logData |
| 26 | + : Array.prototype.slice.call(arguments); |
| 27 | + return util.format.apply(util, wrapErrorsWithInspect(data)); |
| 28 | +} |
| 29 | + |
| 30 | +/** |
| 31 | + * |
| 32 | + * For HTTP (browsers or node.js) use the following configuration params: |
| 33 | + * { |
| 34 | + * "type": "logstashHTTP", // must be present for instantiation |
| 35 | + * "application": "logstash-test", // name of the application |
| 36 | + * "logType": "application", // type of the application |
| 37 | + * "logChannel": "test", // channel of the application |
| 38 | + * "url": "http://lfs-server/_bulk", // logstash receiver servlet URL |
| 39 | + * } |
| 40 | + */ |
| 41 | +function logstashHTTPAppender(config) { |
| 42 | + const sender = axios.create({ |
| 43 | + baseURL: config.url, |
| 44 | + timeout: config.timeout || 5000, |
| 45 | + headers: { 'Content-Type': 'application/x-ndjson' }, |
| 46 | + withCredentials: true, |
| 47 | + }); |
| 48 | + |
| 49 | + return function log(event) { |
| 50 | + const logstashEvent = [ |
| 51 | + { |
| 52 | + index: { |
| 53 | + _index: config.application, |
| 54 | + _type: config.logType, |
| 55 | + }, |
| 56 | + }, |
| 57 | + { |
| 58 | + message: format(event.data), |
| 59 | + context: event.context, |
| 60 | + level: event.level.level / 100, |
| 61 | + level_name: event.level.levelStr, |
| 62 | + channel: config.logChannel, |
| 63 | + datetime: (new Date(event.startTime)).toISOString(), |
| 64 | + extra: {}, |
| 65 | + }, |
| 66 | + ]; |
| 67 | + const logstashJSON = `${JSON.stringify(logstashEvent[0])}\n${JSON.stringify(logstashEvent[1])}\n`; |
| 68 | + |
| 69 | + // send to server |
| 70 | + sender.post('', logstashJSON) |
| 71 | + .catch((error) => { |
| 72 | + if (error.response) { |
| 73 | + console.error(`log4js.logstashHTTP Appender error posting to ${config.url}: ${error.response.status} - ${error.response.data}`); |
| 74 | + return; |
| 75 | + } |
| 76 | + console.error(`log4js.logstashHTTP Appender error: ${error.message}`); |
| 77 | + }); |
| 78 | + }; |
| 79 | +} |
| 80 | + |
| 81 | +function configure(config) { |
| 82 | + return logstashHTTPAppender(config); |
| 83 | +} |
| 84 | + |
| 85 | +module.exports.configure = configure; |
0 commit comments