-
-
Notifications
You must be signed in to change notification settings - Fork 661
/
logger.js
348 lines (294 loc) · 9.21 KB
/
logger.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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
'use strict';
// Log class
const util = require('node:util');
const tty = require('node:tty');
const config = require('haraka-config');
const constants = require('haraka-constants');
let plugins;
const regex = /(^$|[ ="\\])/;
const escape_replace_regex = /["\\]/g;
function stringify (obj) {
let str = '';
let key;
for (key in obj) {
let v = obj[key];
if (v == null) {
str += `${key}="" `;
continue;
}
v = v.toString();
if (regex.test(v)) {
str += `${key}="${v.replace(escape_replace_regex, '\\$&')}" `;
}
else {
str += `${key}=${v} `;
}
}
return str.trim();
}
const logger = exports;
logger.levels = {
DATA: 9,
PROTOCOL: 8,
DEBUG: 7,
INFO: 6,
NOTICE: 5,
WARN: 4,
ERROR: 3,
CRIT: 2,
ALERT: 1,
EMERG: 0,
}
const level_names = Object.keys(logger.levels)
for (const le in logger.levels) {
logger.levels[`LOG${le}`] = logger.levels[le];
logger[`LOG${le}`] = logger.levels[le];
}
logger.formats = {
DEFAULT: "DEFAULT",
LOGFMT: "LOGFMT",
JSON: "JSON",
}
logger.loglevel = logger.levels.WARN;
logger.format = logger.formats.DEFAULT;
logger.timestamps = false;
logger.deferred_logs = [];
logger.name = 'logger'
logger.colors = {
"DATA" : "green",
"PROTOCOL" : "green",
"DEBUG" : "grey",
"INFO" : "cyan",
"NOTICE" : "blue",
"WARN" : "red",
"ERROR" : "red",
"CRIT" : "red",
"ALERT" : "red",
"EMERG" : "red",
}
const stdout_is_tty = tty.isatty(process.stdout.fd);
logger._init = function () {
this.load_log_ini();
this._init_loglevel();
this._init_timestamps();
}
logger.load_log_ini = function () {
this.cfg = config.get('log.ini', {
booleans: [
'+main.timestamps',
]
},
() => {
this.load_log_ini();
});
this.set_loglevel(this.cfg.main.level);
this.set_timestamps(this.cfg.main.timestamps);
this.set_format(this.cfg.main.format);
}
logger.colorize = (color, str) => {
if (!util.inspect.colors[color]) { return str; } // unknown color
return `\u001b[${util.inspect.colors[color][0]}m${str}\u001b[${util.inspect.colors[color][1]}m`;
}
logger.dump_logs = cb => {
while (logger.deferred_logs.length > 0) {
const log_item = logger.deferred_logs.shift();
plugins.run_hooks('log', logger, log_item);
}
// Run callback after flush
if (cb) process.stdout.write('', cb);
return true;
}
if (!util.isFunction) {
util.isFunction = functionToCheck => {
const getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
};
}
logger.dump_and_exit = function (code) {
this.dump_logs(() => {
if (util.isFunction(code)) return code();
process.exit(code);
});
}
logger.log = (level, data, logobj) => {
if (level === 'PROTOCOL') {
data = data.replace(/\n/g, '\\n');
}
data = data.replace(/\r/g, '\\r').replace(/\n$/, '');
const item = { level, data, obj: logobj};
// buffer until plugins are loaded
const emptyPluginList = !plugins || Array.isArray(plugins.plugin_list) && !plugins.plugin_list.length;
if (emptyPluginList) {
logger.deferred_logs.push(item);
return true;
}
// process buffered logs
while (logger.deferred_logs.length > 0) {
const log_item = logger.deferred_logs.shift();
plugins.run_hooks('log', logger, log_item);
}
plugins.run_hooks('log', logger, item);
return true;
}
logger.log_respond = (retval, msg, data) => {
// any other return code is irrelevant
if (retval !== constants.cont) return false;
let timestamp_string = '';
if (logger.timestamps) timestamp_string = `${new Date().toISOString()} `;
const color = logger.colors[data.level];
if (color && stdout_is_tty) {
process.stdout.write(`${timestamp_string}${logger.colorize(color,data.data)}\n`);
}
else {
process.stdout.write(`${timestamp_string}${data.data}\n`);
}
return true;
}
logger.set_loglevel = function (level) {
if (level === undefined || level === null) return;
const loglevel_num = parseInt(level);
if (typeof level === 'string') {
this.log('INFO', `loglevel: ${level.toUpperCase()}`);
logger.loglevel = logger.levels[level.toUpperCase()];
}
else {
logger.loglevel = loglevel_num;
}
if (!Number.isInteger(logger.loglevel)) {
this.log('WARN', `invalid loglevel: ${level} defaulting to LOGWARN`);
logger.loglevel = logger.levels.WARN;
}
}
logger.set_format = function (format) {
if (format) {
logger.format = logger.formats[format.toUpperCase()];
this.log('INFO', `log format: ${format.toUpperCase()}`);
}
else {
logger.format = null;
}
if (!logger.format) {
this.log('WARN', `invalid log format: ${format} defaulting to DEFAULT`);
logger.format = logger.formats.DEFAULT;
}
}
logger._init_loglevel = function () {
const _loglevel = config.get('loglevel', 'value', () => {
this._init_loglevel();
});
this.set_loglevel(_loglevel);
}
logger.would_log = level => {
if (logger.loglevel < level) return false;
return true;
}
logger.set_timestamps = value => {
logger.timestamps = !!value;
}
logger._init_timestamps = function () {
const _timestamps = config.get('log_timestamps', 'value', () => {
this._init_timestamps();
});
// If we've already been toggled to true by the cfg, we should respect this.
this.set_timestamps(logger.timestamps || _timestamps);
}
logger._init();
logger.log_if_level = (level, key, origin) => function () {
if (logger.loglevel < logger[key]) return;
let logobj = {
level,
uuid: '-',
origin: (origin || 'core'),
message: ''
};
for (const data of arguments) {
if (typeof data !== 'object') {
logobj.message += (data);
continue;
}
if (!data) continue;
// if the object is a connection, add the connection id
if (data.constructor?.name === 'Connection') {
logobj.uuid = data.uuid;
if (data.tran_count > 0) logobj.uuid += `.${data.tran_count}`;
}
else if (data instanceof plugins.Plugin) {
logobj.origin = data.name;
}
else if (Object.hasOwn(data, 'name')) { // outbound
logobj.origin = data.name;
if (Object.hasOwn(data, 'uuid')) logobj.uuid = data.uuid;
if (data.todo?.uuid) logobj.uuid = data.todo.uuid; // outbound/hmail
}
else if (
logger.format === logger.formats.LOGFMT && data.constructor === Object) {
logobj = Object.assign(logobj, data);
}
else if (
logger.format === logger.formats.JSON && data.constructor === Object) {
logobj = Object.assign(logobj, data);
}
else if (Object.hasOwn(data, 'uuid')) { // outbound/client_pool
logobj.uuid = data.uuid;
}
else if (data.constructor === Object) {
if (!logobj.message.endsWith(' ')) logobj.message += ' ';
logobj.message += (stringify(data));
}
else {
logobj.message += (util.inspect(data));
}
}
switch (logger.format) {
case logger.formats.LOGFMT:
logger.log(
level,
stringify(logobj)
);
break
case logger.formats.JSON:
logger.log(
level,
JSON.stringify(logobj)
);
break
case logger.formats.DEFAULT:
default:
logger.log(
level,
`[${logobj.level}] [${logobj.uuid}] [${logobj.origin}] ${logobj.message}`
);
}
return true;
}
logger.add_log_methods = (object, logName) => {
if (!object) return
if (typeof object === 'function') {
// add logging methods to class prototypes (Connection, Plugin, etc.)
for (const level of level_names.map(l => l.toLowerCase())) {
object.prototype[`log${level}`] = (function (level) {
return function () {
logger[level].apply(logger, [ this, ...arguments ]);
};
})(`log${level}`);
}
}
else if (typeof object === 'object') {
// add logging methods to objects
for (const level of level_names) {
// objects gets log function names: loginfo, logwarn, logdebug, ...
const fnNames = [`log${level.toLowerCase()}`]
// logger also gets short names
if (Object.hasOwn(object, 'name') && object.name === 'logger') {
fnNames.push(level.toLowerCase())
}
for (const fnName of fnNames) {
if (Object.hasOwn(object, fnName)) continue; // already added
object[fnName] = logger.log_if_level(level, `LOG${level}`, logName);
}
}
}
}
logger.add_log_methods(logger);
// load these down here so it sees all the logger methods compiled above
plugins = require('./plugins');