@ditjenpajakri/elasticsearch-logging 2.0.1 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/apm.env +6 -0
  2. package/lib.js +213 -144
  3. package/package.json +2 -1
  4. package/test +1 -0
package/apm.env ADDED
@@ -0,0 +1,6 @@
1
+ LOG_ES_HOST=https://10.244.66.34:9200
2
+ LOG_ES_PASS=jkljkl2020
3
+ LOG_ES_VAR_A_AA=aaa
4
+ LOG_ES_VAR_A_BB=bbb
5
+ LOG_ES_VAR_B=ccc
6
+ LOG_ES_INDEX=test-a-%{DATE}
package/lib.js CHANGED
@@ -1,170 +1,239 @@
1
1
  #! /usr/bin/env node
2
- 'use strict'
2
+ "use strict";
3
+
4
+ const { Client } = require("@elastic/elasticsearch");
5
+ const split = require("split2");
6
+ const pump = require("pump");
7
+ const fs = require("fs");
8
+ const { configDotenv } = require("dotenv");
9
+
10
+ /**
11
+ * Performs a deep merge of objects and returns new object. Does not modify
12
+ * objects (immutable) and merges arrays via concatenation.
13
+ *
14
+ * @param {...object} objects - Objects to merge
15
+ * @returns {object} New object with merged key/values
16
+ */
17
+ function mergeDeep(...objects) {
18
+ const isObject = (obj) => obj && typeof obj === "object";
19
+
20
+ return objects.reduce((prev, obj) => {
21
+ Object.keys(obj).forEach((key) => {
22
+ const pVal = prev[key];
23
+ const oVal = obj[key];
24
+
25
+ if (Array.isArray(pVal) && Array.isArray(oVal)) {
26
+ prev[key] = pVal.concat(...oVal);
27
+ } else if (isObject(pVal) && isObject(oVal)) {
28
+ prev[key] = mergeDeep(pVal, oVal);
29
+ } else {
30
+ prev[key] = oVal;
31
+ }
32
+ });
3
33
 
4
- const { Client } = require('@elastic/elasticsearch')
5
- const split = require('split2')
6
- const pump = require('pump')
34
+ return prev;
35
+ }, {});
36
+ }
7
37
 
8
38
  function setDateTimeString(value) {
9
- if (typeof value === 'object' && value.hasOwnProperty('time')) {
10
- if (
11
- (typeof value.time === 'string' && value.time.length) ||
12
- (typeof value.time === 'number' && value.time >= 0)
13
- ) {
14
- return new Date(value.time).toISOString()
15
- }
39
+ if (typeof value === "object" && value.hasOwnProperty("time")) {
40
+ if (
41
+ (typeof value.time === "string" && value.time.length) ||
42
+ (typeof value.time === "number" && value.time >= 0)
43
+ ) {
44
+ return new Date(value.time).toISOString();
16
45
  }
17
- return new Date().toISOString()
46
+ }
47
+ return new Date().toISOString();
18
48
  }
19
49
 
20
- function initializeBulkHandler (opts, client, splitter) {
21
- const esVersion = Number(opts.esVersion || opts['es-version']) || 7
22
- const index = opts.index || 'pino'
23
- const buildIndexName = typeof index === 'function' ? index : null
24
- const type = esVersion >= 7 ? undefined : (opts.type || 'log')
25
- const opType = esVersion >= 7 ? (opts.opType || opts.op_type) : undefined
26
-
27
- // Resurrect connection pool on destroy
28
- splitter.destroy = () => {
29
- if (typeof client.connectionPool.resurrect === 'function') {
30
- client.connectionPool.resurrect({ name: 'elasticsearch-js' })
31
- }
50
+ function initializeBulkHandler(opts, client, splitter) {
51
+ const esVersion = Number(opts.esVersion || opts["es-version"]) || 7;
52
+ const index = opts.index || "pino";
53
+ const buildIndexName = typeof index === "function" ? index : null;
54
+ // const type = esVersion >= 7 ? undefined : opts.type || "log";
55
+ const opType = esVersion >= 7 ? opts.opType || opts.op_type : undefined;
56
+
57
+ // Resurrect connection pool on destroy
58
+ splitter.destroy = () => {
59
+ if (typeof client.connectionPool.resurrect === "function") {
60
+ client.connectionPool.resurrect({ name: "elasticsearch-js" });
32
61
  }
33
-
34
- const bulkInsert = client.helpers.bulk({
35
- datasource: splitter,
36
- flushBytes: opts.flushBytes || opts['flush-bytes'] || 1000,
37
- flushInterval: opts.flushInterval || opts['flush-interval'] || 30000,
38
- refreshOnCompletion: getIndexName(),
39
- onDocument (doc) {
40
- const date = doc.time || doc['@timestamp']
41
- if (opType === 'create') {
42
- doc['@timestamp'] = date
43
- }
44
-
45
- return {
46
- create: {
47
- _index: getIndexName(date),
48
- // _type: type,
49
- }
50
- }
51
- },
52
- onDrop (doc) {
53
- const error = new Error('Dropped document')
54
- error.document = doc
55
- splitter.emit('insertError', error)
62
+ };
63
+
64
+ const bulkInsert = client.helpers.bulk({
65
+ datasource: splitter,
66
+ flushBytes: opts.flushBytes || opts["flush-bytes"] || 1000,
67
+ flushInterval: opts.flushInterval || opts["flush-interval"] || 30000,
68
+ refreshOnCompletion: getIndexName(),
69
+ onDocument(doc) {
70
+ const date = doc.time || doc["@timestamp"];
71
+ if (opType === "create") {
72
+ doc["@timestamp"] = date;
56
73
  }
57
- })
58
-
59
- bulkInsert.then(
60
- (stats) => splitter.emit('insert', stats),
61
- (err) => splitter.emit('error', err)
62
- )
63
-
64
- function getIndexName (time = new Date().toISOString()) {
65
- if (buildIndexName) {
66
- return buildIndexName(time)
67
- }
68
- return index.replace('%{DATE}', time.substring ? time.substring(0, 10) : "")
74
+
75
+ return {
76
+ create: {
77
+ _index: getIndexName(date),
78
+ // _type: type,
79
+ },
80
+ };
81
+ },
82
+ onDrop(doc) {
83
+ const error = new Error("Dropped document");
84
+ error.document = doc;
85
+ splitter.emit("insertError", error);
86
+ },
87
+ });
88
+
89
+ bulkInsert.then(
90
+ (stats) => splitter.emit("insert", stats),
91
+ (err) => splitter.emit("error", err)
92
+ );
93
+
94
+ function getIndexName(time = new Date().toISOString()) {
95
+ if (buildIndexName) {
96
+ return buildIndexName(time);
69
97
  }
98
+ return index.replace(
99
+ "%{DATE}",
100
+ time.substring ? time.substring(0, 10) : ""
101
+ );
70
102
  }
71
-
103
+ }
72
104
 
73
105
  function pinoElasticSearch(opts = {}) {
74
- const splitter = split(function (line) {
75
- let value
76
- try {
77
- value = JSON.parse(line)
78
- } catch (error) {
79
- console.log(line);
80
- // this.emit('unknown', line, error)
81
- return
82
- }
83
-
84
- if (typeof value === 'boolean') {
85
- this.emit('unknown', line, 'Boolean value ignored')
86
- return
87
- }
88
- if (value === null) {
89
- this.emit('unknown', line, 'Null value ignored')
90
- return
91
- }
92
- if (typeof value !== 'object') {
93
- value = {
94
- data: value,
95
- ['@timestamp']: setDateTimeString(value)
96
- }
97
- } else {
98
- if (value['@timestamp'] === undefined) {
99
- value['@timestamp'] = setDateTimeString(value)
100
- }
101
- }
102
- return value
103
- }, { autoDestroy: true })
104
-
105
- const clientOpts = {
106
- node: opts.node,
107
- auth: opts.auth,
108
- // cloud: opts.cloud,
109
- tls: {
110
- rejectUnauthorized: false
111
- }
112
- }
106
+ const splitter = split(
107
+ function (line) {
108
+ let value;
109
+ try {
110
+ value = JSON.parse(line);
111
+ } catch (error) {
112
+ console.log(line);
113
+ // this.emit('unknown', line, error)
114
+ return;
115
+ }
113
116
 
114
- if (opts.caFingerprint) {
115
- clientOpts.caFingerprint = opts.caFingerprint
116
- }
117
+ if (typeof value === "boolean") {
118
+ this.emit("unknown", line, "Boolean value ignored");
119
+ return;
120
+ }
121
+ if (value === null) {
122
+ this.emit("unknown", line, "Null value ignored");
123
+ return;
124
+ }
125
+ if (typeof value !== "object") {
126
+ value = {
127
+ data: value,
128
+ ["@timestamp"]: setDateTimeString(value),
129
+ };
130
+ } else {
131
+ value["message"] = value.msg || "-";
117
132
 
118
- if (opts.Connection) {
119
- clientOpts.Connection = opts.Connection
120
- }
133
+ if (value.msg) delete value.msg;
121
134
 
122
- if (opts.ConnectionPool) {
123
- clientOpts.ConnectionPool = opts.ConnectionPool
124
- }
135
+ value["@timestamp"] = setDateTimeString(value);
136
+
137
+ if (value.time) delete value.time;
138
+ }
139
+ return mergeDeep(value, opts.additionalObject);
140
+ },
141
+ { autoDestroy: true }
142
+ );
143
+
144
+ const clientOpts = {
145
+ node: opts.node,
146
+ auth: opts.auth,
147
+ // cloud: opts.cloud,
148
+ tls: {
149
+ rejectUnauthorized: false,
150
+ },
151
+ };
152
+
153
+ if (opts.caFingerprint) {
154
+ clientOpts.caFingerprint = opts.caFingerprint;
155
+ }
125
156
 
126
- const client = new Client(clientOpts)
127
- console.log("Logging to elasticsearch...");
128
- console.log("Any line showing up here means that the line was not logged to elasticsearch.");
129
- client.diagnostic.on('resurrect', () => {
130
- initializeBulkHandler(opts, client, splitter)
131
- })
157
+ if (opts.Connection) {
158
+ clientOpts.Connection = opts.Connection;
159
+ }
160
+
161
+ if (opts.ConnectionPool) {
162
+ clientOpts.ConnectionPool = opts.ConnectionPool;
163
+ }
132
164
 
133
- initializeBulkHandler(opts, client, splitter)
165
+ const client = new Client(clientOpts);
166
+ console.log("Logging to elasticsearch...");
167
+ console.log(
168
+ "Any line showing up here means that the line was not logged to elasticsearch."
169
+ );
170
+ client.diagnostic.on("resurrect", () => {
171
+ initializeBulkHandler(opts, client, splitter);
172
+ });
134
173
 
135
- return splitter
174
+ initializeBulkHandler(opts, client, splitter);
175
+
176
+ return splitter;
136
177
  }
137
178
 
138
179
  function start(opts) {
139
- console.log('opts', opts)
140
- const stream = pinoElasticSearch(opts)
141
-
142
- stream.on('unknown', (line, error) => {
143
- console.error('Elasticsearch client json error in line:\n' + line + '\nError:', error)
144
- })
145
- stream.on('error', (error) => {
146
- console.error('Elasticsearch client error:', error)
147
- })
148
- stream.on('insertError', (error) => {
149
- console.log(JSON.stringify(error))
150
- console.error('Elasticsearch server error:', error)
151
- })
152
-
153
- pump(process.stdin, stream)
180
+ console.log("opts", opts);
181
+ const stream = pinoElasticSearch(opts);
182
+
183
+ stream.on("unknown", (line, error) => {
184
+ console.error(
185
+ "Elasticsearch client json error in line:\n" + line + "\nError:",
186
+ error
187
+ );
188
+ });
189
+ stream.on("error", (error) => {
190
+ console.error("Elasticsearch client error:", error);
191
+ });
192
+ stream.on("insertError", (error) => {
193
+ console.log(JSON.stringify(error));
194
+ console.error("Elasticsearch server error:", error);
195
+ });
196
+
197
+ pump(process.stdin, stream);
154
198
  }
155
199
 
156
- module.exports = pinoElasticSearch
200
+ module.exports = pinoElasticSearch;
157
201
 
158
202
  if (require.main === module) {
159
- start({
160
- node: process.env.LOG_ES_HOST || 'http://localhost:9200',
161
- auth: {
162
- username: process.env.LOG_ES_USER || 'elastic',
163
- password: process.env.LOG_ES_PASS || 'changeme'
164
- },
165
- index: process.env.LOG_ES_INDEX || 'DJP-%{DATE}',
166
- flushBytes: process.env.LOG_ES_FLUSH_BYTES ? parseInt(process.env.LOG_ES_FLUSH_BYTES) : undefined,
167
- flushInterval: process.env.LOG_ES_FLUSH_INTERVAL ? parseInt(process.env.LOG_ES_FLUSH_INTERVAL) : undefined,
168
- rejectUnauthorized: process.env.LOG_ES_REJECT_UNAUTHORIZED === 'true' ? true : false,
169
- })
170
- }
203
+ const fileEnv = process.argv[2];
204
+
205
+ if (fileEnv && fs.statSync(fileEnv)) {
206
+ configDotenv({
207
+ path: fileEnv,
208
+ });
209
+ }
210
+
211
+ const additionalFields = Object.keys(process.env).filter((key) =>
212
+ key.startsWith("LOG_ES_VAR_")
213
+ );
214
+
215
+ const additionalObject = {};
216
+ additionalFields.forEach((field) => {
217
+ const value = process.env[field];
218
+ const key = field.slice(11);
219
+ additionalObject[key] = value;
220
+ });
221
+
222
+ start({
223
+ node: process.env.LOG_ES_HOST || "http://localhost:9200",
224
+ additionalObject,
225
+ auth: {
226
+ username: process.env.LOG_ES_USER || "elastic",
227
+ password: process.env.LOG_ES_PASS || "changeme",
228
+ },
229
+ index: process.env.LOG_ES_INDEX || "logs-apm-%{DATE}",
230
+ flushBytes: process.env.LOG_ES_FLUSH_BYTES
231
+ ? parseInt(process.env.LOG_ES_FLUSH_BYTES)
232
+ : undefined,
233
+ flushInterval: process.env.LOG_ES_FLUSH_INTERVAL
234
+ ? parseInt(process.env.LOG_ES_FLUSH_INTERVAL)
235
+ : undefined,
236
+ rejectUnauthorized:
237
+ process.env.LOG_ES_REJECT_UNAUTHORIZED === "true" ? true : false,
238
+ });
239
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ditjenpajakri/elasticsearch-logging",
3
- "version": "2.0.1",
3
+ "version": "2.2.1",
4
4
  "description": "Elasticsearch ",
5
5
  "main": "lib.js",
6
6
  "bin": {
@@ -17,6 +17,7 @@
17
17
  "license": "MIT",
18
18
  "dependencies": {
19
19
  "@elastic/elasticsearch": "8",
20
+ "dotenv": "^16.4.5",
20
21
  "pump": "^3.0.0",
21
22
  "split2": "^4.2.0"
22
23
  },
package/test ADDED
@@ -0,0 +1 @@
1
+ {"a": "1234"}