UNPKG

2.7 kBJavaScriptView Raw
1const SplunkLogger = require('splunk-logging').Logger;
2
3let _splunkConfig; // Define _splunkConfig variable
4let _index; // Define _index variable
5let Logger; // Define Logger variable
6
7/**
8 *
9 * @method init
10 * @description initiate the configuration for splunk
11 * @param {*} splunkConfig
12 * @returns
13 */
14function 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 * @method initateSplunkMetaData
30 * @param {*} splunkMetadata
31 * @param {*} context
32 * @returns
33 */
34function 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 * @method initiatePayload
50 * @param {*} context
51 * @param {*} splunkMetadata
52 * @returns
53 */
54function 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 * @method getPayloadItems
82 * @param {*} context
83 * @returns
84 */
85function 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 * @method splunkHooks
95 * @param {*} [splunkMetadata={}]
96 * @returns
97 */
98function 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 * @method sendLogToSplunk
112 * @param {*} payload
113 */
114function 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
122module.exports.splunkHooks = splunkHooks;
123module.exports.splunk = init;