-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.js
91 lines (82 loc) · 2.6 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
'use strict';
/**
* logstashHTTP appender sends JSON formatted log events to logstashHTTP receivers.
*/
const util = require('util');
const axios = require('axios');
function wrapErrorsWithInspect(items) {
return items.map((item) => {
if ((item instanceof Error) && item.stack) {
return {
inspect: function () {
return `${util.format(item)}\n${item.stack}`;
}
};
}
return item;
});
}
function format(logData) {
return util.format.apply(util, wrapErrorsWithInspect(logData));
}
/**
*
* For HTTP (browsers or node.js) use the following configuration params:
* {
* "type": "@log4js-node/logstash-http", // must be present for instantiation
* "application": "logstash-test", // name of the application
* "logType": "application", // type of the application
* "logChannel": "test", // channel of the application
* "url": "http://lfs-server/_bulk", // logstash receiver servlet URL
* }
* @param {import('../types').LogstashHTTPAppender} config
*/
function logstashHTTPAppender(config) {
const sender = axios.create({
baseURL: config.url,
timeout: config.timeout || 5000,
headers: { 'Content-Type': 'application/x-ndjson' },
withCredentials: true,
// The user should pass in the correct Agent type for their url
// since their url won't change after config this should be fine
httpAgent: config.agent,
httpsAgent: config.agent,
});
return function log(event) {
const logstashEvent = [
{
index: {
_index: config.application,
_type: config.logType,
},
},
{
message: format(event.data),
context: event.context,
level: event.level.level / 100,
level_name: event.level.levelStr,
channel: config.logChannel,
datetime: (new Date(event.startTime)).toISOString(),
extra: {},
},
];
const logstashJSON = `${JSON.stringify(logstashEvent[0])}\n${JSON.stringify(logstashEvent[1])}\n`;
// send to server
sender.post('', logstashJSON)
.catch((error) => {
if (error.response) {
// eslint-disable-next-line
console.error(
`log4js.logstashHTTP Appender error posting to ${config.url}: ${error.response.status} - ${JSON.stringify(error.response.data)}`
);
} else {
// eslint-disable-next-line
console.error(`log4js.logstashHTTP Appender error: ${error.message}`);
}
});
};
}
function configure(config) {
return logstashHTTPAppender(config);
}
module.exports.configure = configure;