-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
199 lines (178 loc) · 5.49 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
/*
* moleculer
* Copyright (c) 2019 MoleculerJS (https://github.com/moleculerjs/moleculer)
* MIT Licensed
*/
/**
* @typedef {Object} ElasticLoggerOptions
* @property {import('@elastic/elasticsearch').ClientOptions} clientOptions Elasticsearch client options
* @property {string | null} [index=null] Elasticsearch index
* @property {string | null} [pipeline=null] Elasticsearch pipeline from Ingest Pipelines
* @property {string} [source='moleculer'] Default is process.env.MOL_NODE_NAME if set or 'moleculer'
* @property {string} [hostname='hostname'] Hostname, default is machine hostname 'os.hostname()'
* @property {Function} [objectPrinter=null] Callback function for object printer, default is 'JSON.stringify'
* @property {number} [interval=5000] Date uploading interval in milliseconds, default is 10000
* @property {string[]} [excludeModules=[]] Exclude modules from logs, 'broker', 'registry' etc.
*/
const _ = require('lodash')
const { Client } = require('@elastic/elasticsearch')
const BaseLogger = require('moleculer').Loggers.Base
const { hostname } = require('os')
fetch.Promise = Promise
const isObject = (o) => o !== null && typeof o === 'object' && !(o instanceof String)
Date.prototype.yyyymmdd = function () {
// getMonth() is zero-based
const mm = this.getMonth() + 1
const dd = this.getDate()
return [this.getFullYear(), (mm > 9 ? '' : '0') + mm, (dd > 9 ? '' : '0') + dd].join('')
}
const replacerFunc = () => {
const visited = new WeakSet()
return (key, value) => {
if (typeof value === 'object' && value !== null) {
if (visited.has(value)) {
return
}
visited.add(value)
}
return value
}
}
/**
* ElasticLogger logger for Moleculer
* send logs directly to elastic
* @class ElasticLogger
* @constructor
* @extends {BaseLogger}
*/
class ElasticLogger extends BaseLogger {
/**
* Creates an instance of ElasticLogger.
* @param {ElasticLoggerOptions} opts
* @memberof ElasticLogger
*/
constructor(opts = {}) {
super(opts)
/**
* @type {ElasticLoggerOptions}
*/
const defaultOptions = {
clientOptions: {
node: 'http://localhost:9200',
tls: {
//ca: readFileSync('/ca.crt'),
rejectUnauthorized: false,
},
},
index: null,
pipeline: null,
source: process.env.MOL_NODE_NAME || 'moleculer',
hostname: hostname(),
objectPrinter: null,
interval: 5 * 1000,
excludeModules: [],
}
this.opts = _.defaultsDeep(this.opts, defaultOptions)
this.queue = []
this.timer = null
this.client = {}
}
/**
* Initialize logger.
* @param {LoggerFactory} loggerFactory
*/
init(loggerFactory) {
super.init(loggerFactory)
this.objectPrinter = this.opts.objectPrinter
? this.opts.objectPrinter
: (o) => JSON.stringify(o, replacerFunc(), 2)
if (this.opts.interval > 0) {
this.timer = setInterval(() => this.flush(), this.opts.interval)
this.timer.unref()
}
this.client = new Client(this.opts.clientOptions)
}
/**
* Stopping logger
*/
stop() {
if (this.timer) {
clearInterval(this.timer)
this.timer = null
}
return this.flush()
}
/**
* Generate a new log handler.
* @param {object} bindings
*/
getLogHandler(bindings) {
const level = bindings ? this.getLogLevel(bindings.mod) : null
if (!level) return null
const printArgs = (args) => {
return args.map((p) => {
if (isObject(p) || Array.isArray(p)) return this.objectPrinter(p)
if (typeof p === 'string') return p.trim()
return p
})
}
const levelIdx = BaseLogger.LEVELS.indexOf(level)
return (type, args) => {
const typeIdx = BaseLogger.LEVELS.indexOf(type)
if (typeIdx > levelIdx) return
// allow only `error` and `fatal` from broker
if (this.opts.excludeModules.includes(bindings.mod) && !(bindings.mod === 'broker' && typeIdx <= 1)) return
this.queue.push({
ts: new Date(),
level: type,
msg: printArgs(args).join(' '),
bindings,
})
if (!this.opts.interval) this.flush()
}
}
/**
* Flush queued log entries to ElasticLogger.
*/
flush() {
if (this.queue.length > 0) {
const rows = Array.from(this.queue)
this.queue.length = 0
const data = rows.map((row) => [
{
index: {
_index: this.opts.index || `moleculer-${row.ts.yyyymmdd()}`,
pipeline: this.opts.pipeline,
},
},
{
timestamp: row.ts.getTime(),
level: row.level,
message: row.msg,
nodeID: row.bindings.nodeID,
namespace: row.bindings.ns,
service: row.bindings.svc,
version: row.bindings.ver,
source: this.opts.source,
tags: [process.env.NODE_ENV],
hostname: this.opts.hostname,
},
])
const operations = _.flatten(data)
return this.client
.bulk({ refresh: true, operations })
.then((res) => {
if (res.errors) {
console.info(`Logs are uploaded to ELK server, but has errors: ${res.errors}`)
const errorDocs = res.items.filter((doc) => doc.index.status > 300)
console.log({ errorDocs: JSON.stringify(errorDocs, null, 2) })
}
})
.catch((err) => {
console.warn(`Unable to upload logs to ELK server. Error:${err.message}`, err)
})
}
return this.broker.Promise.resolve()
}
}
module.exports = ElasticLogger