1 | const SplunkLogger = require('splunk-logging').Logger;
|
2 |
|
3 | let _splunkConfig;
|
4 | let _index;
|
5 | let Logger;
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 | function init (splunkConfig) {
|
15 | if (!splunkConfig) {
|
16 | throw new Error('No Splunk Token and URL specified');
|
17 | }
|
18 | _splunkConfig = splunkConfig;
|
19 | _index = splunkConfig.index ? splunkConfig.index : 'main';
|
20 | Logger = new SplunkLogger(_splunkConfig);
|
21 |
|
22 | return context => {
|
23 | return context;
|
24 | };
|
25 | }
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 | function initateSplunkMetaData (splunkMetadata, context) {
|
35 | if (Object.keys(splunkMetadata).length === 0) {
|
36 | splunkMetadata = {
|
37 | source: context.path,
|
38 | sourcetype: context.params.provider,
|
39 | index: _index,
|
40 | host: context.app.settings.host,
|
41 | port: context.app.settings.port
|
42 | };
|
43 | }
|
44 | return splunkMetadata;
|
45 | }
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 |
|
54 | function initiatePayload (context, splunkMetadata) {
|
55 | let _messageForPayload = getPayloadItems(context);
|
56 | let _severity = 'info';
|
57 | if (context.type === 'error') {
|
58 | const _err = context.error;
|
59 | _messageForPayload = {
|
60 | message: _err.message,
|
61 | name: _err.name,
|
62 | code: _err.code,
|
63 | className: _err.className,
|
64 | info: _err.info,
|
65 | data: _err.dat
|
66 | };
|
67 | _severity = 'error';
|
68 | }
|
69 |
|
70 | const payload = {
|
71 | message: _messageForPayload,
|
72 | metadata: splunkMetadata,
|
73 | severity: _severity
|
74 | };
|
75 |
|
76 | return payload;
|
77 | }
|
78 |
|
79 |
|
80 |
|
81 |
|
82 |
|
83 |
|
84 |
|
85 | function getPayloadItems (context) {
|
86 | const _messageForPayload = (context.type === 'before') ? context.data : context.result;
|
87 | return _messageForPayload && context.method === 'find'
|
88 | ? _messageForPayload.data || _messageForPayload
|
89 | : _messageForPayload;
|
90 | }
|
91 |
|
92 |
|
93 |
|
94 |
|
95 |
|
96 |
|
97 |
|
98 | function splunkHooks (splunkMetadata = {}) {
|
99 | return context => {
|
100 | splunkMetadata = initateSplunkMetaData(splunkMetadata, context);
|
101 |
|
102 | const payload = initiatePayload(context, splunkMetadata);
|
103 |
|
104 | sendLogToSplunk(payload);
|
105 | return context;
|
106 | };
|
107 | }
|
108 |
|
109 |
|
110 |
|
111 |
|
112 |
|
113 |
|
114 | function sendLogToSplunk (payload) {
|
115 | Logger.send(payload, function (err, resp, body) {
|
116 | if (!err) {
|
117 | console.log('Successfully sent the message to splunk', body);
|
118 | }
|
119 | });
|
120 | }
|
121 |
|
122 | module.exports.splunkHooks = splunkHooks;
|
123 | module.exports.splunk = init;
|