forked from vanthome/winston-elasticsearch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
209 lines (187 loc) · 5.34 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
'use strict';
const util = require('util');
const fs = require('fs');
const Promise = require('promise');
const stream = require('stream');
const winston = require('winston');
const moment = require('moment');
const _ = require('lodash');
const retry = require('retry');
const elasticsearch = require('elasticsearch');
const defaultTransformer = require('./transformer');
const BulkWriter = require('./bulk_writer');
/**
* Constructor
*/
const Elasticsearch = function Elasticsearch(options) {
this.options = options || {};
if (!options.timestamp) {
this.options.timestamp = function timestamp() { return new Date().toISOString(); };
}
// Enforce context
if (!(this instanceof Elasticsearch)) {
return new Elasticsearch(options);
}
// Set defaults
const defaults = {
level: 'info',
index: null,
indexPrefix: 'logs',
indexSuffixPattern: 'YYYY.MM.DD',
messageType: 'log',
transformer: defaultTransformer,
ensureMappingTemplate: true,
flushInterval: 2000,
waitForActiveShards: 1,
handleExceptions: false
};
_.defaults(options, defaults);
winston.Transport.call(this, options);
// Use given client or create one
if (options.client) {
this.client = options.client;
} else {
// As we don't want to spam stdout, create a null stream
// to eat any log output of the ES client
const NullStream = function NullStream() {
stream.Writable.call(this);
};
util.inherits(NullStream, stream.Writable);
// eslint-disable-next-line no-underscore-dangle
NullStream.prototype._write = function _write(chunk, encoding, next) {
next();
};
const defaultClientOpts = {
clientOpts: {
log: [
{
type: 'stream',
level: 'error',
stream: new NullStream()
}
]
}
};
_.defaults(options, defaultClientOpts);
// Create a new ES client
// http://localhost:9200 is the default of the client already
this.client = new elasticsearch.Client(this.options.clientOpts);
}
this.bulkWriter = new BulkWriter(
this.client,
options.flushInterval,
options.waitForActiveShards,
options.maxItemsAfterFlush
);
this.bulkWriter.start();
// Conduct initial connection check (sets connection state for further use)
this.checkEsConnection().then((connectionOk) => {});
return this;
};
util.inherits(Elasticsearch, winston.Transport);
Elasticsearch.prototype.name = 'elasticsearch';
/**
* log() method
*/
Elasticsearch.prototype.log = function log(level, message, meta, callback) {
const logData = {
message,
level,
meta,
timestamp: this.options.timestamp()
};
const entry = this.options.transformer(logData);
this.bulkWriter.append(
this.getIndexName(this.options),
this.options.messageType,
entry
);
callback(); // write is deferred, so no room for errors here :)
};
Elasticsearch.prototype.getIndexName = function getIndexName(options) {
let indexName = options.index;
if (indexName === null) {
const now = moment();
const dateString = now.format(options.indexSuffixPattern);
indexName = options.indexPrefix + '-' + dateString;
}
return indexName;
};
Elasticsearch.prototype.checkEsConnection = function checkEsConnection() {
const thiz = this;
thiz.esConnection = false;
const operation = retry.operation({
retries: 3,
factor: 3,
minTimeout: 1 * 1000,
maxTimeout: 60 * 1000,
randomize: false
});
return new Promise((fulfill, reject) => {
operation.attempt((currentAttempt) => {
thiz.client.ping().then(
(res) => {
thiz.esConnection = true;
// Ensure mapping template is existing if desired
if (thiz.options.ensureMappingTemplate) {
thiz.ensureMappingTemplate(fulfill, reject);
} else {
fulfill(true);
}
},
(err) => {
if (operation.retry(err)) {
return;
}
thiz.esConnection = false;
thiz.emit('error', err);
reject(new Error('Cannot connect to ES'));
}
);
});
});
};
Elasticsearch.prototype.search = function search(q) {
const index = this.getIndexName(this.options);
const query = {
index,
q
};
return this.client.search(query);
};
Elasticsearch.prototype.ensureMappingTemplate = function ensureMappingTemplate(fulfill, reject) {
const thiz = this;
// eslint-disable-next-line prefer-destructuring
let mappingTemplate = thiz.options.mappingTemplate;
if (mappingTemplate === null || typeof mappingTemplate === 'undefined') {
const rawdata = fs.readFileSync('index-template-mapping.json');
mappingTemplate = JSON.parse(rawdata);
}
const tmplCheckMessage = {
name: 'template_' + thiz.options.indexPrefix
};
thiz.client.indices.getTemplate(tmplCheckMessage).then(
(res) => {
fulfill(res);
},
(res) => {
if (res.status && res.status === 404) {
const tmplMessage = {
name: 'template_' + thiz.options.indexPrefix,
create: true,
body: mappingTemplate
};
thiz.client.indices.putTemplate(tmplMessage).then(
(res1) => {
fulfill(res1);
},
(err1) => {
reject(err1);
}
);
}
}
);
};
winston.transports.Elasticsearch = Elasticsearch;
module.exports = Elasticsearch;