-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathlogging.js
More file actions
464 lines (416 loc) · 14.5 KB
/
Copy pathlogging.js
File metadata and controls
464 lines (416 loc) · 14.5 KB
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
'use strict';
const fs = require('fs');
const mkdir = require('mkdirp');
const os = require('os');
const path = require('path');
const util = require('util');
const configService = require('./config')
const stats = require('./stats')
const assert = require('assert')
const uuid = require('uuid')
const cluster = require('cluster')
const CONSOLE_LOG_TAG = 'microgateway-core logging';
var logger = null;
var logToConsole = false;
module.exports.init = function init(stubConfig, options) {
if (!process.env.CurrentOrgName && !process.env.CurrentEnvironmentName && options) {
process.env.CurrentOrgName = options.org;
process.env.CurrentEnvironmentName = options.env;
}
const config = stubConfig || configService.get()
assert(config, 'must have config')
assert(config.uid, 'config must have uid');
const uid = config.uid || uuid.v1();
const logConfig = config.edgemicro.logging;
assert(logConfig, 'must have config.edgemicro.logging in config');
logToConsole = !!logConfig.to_console;
var rotation = 0;
const logDir = logConfig.dir || process.cwd();
var logFilePath = _calculateLogFilePath(logDir, uid, rotation);
mkdir.sync(logDir);
statsTimer(logConfig.stats_log_interval);
// using a WriteStream here causes excessive memory growth under high load (with node v0.12.6, jul 2015)
var logFileFd;
var logFailWarn = false;
var writeInProgress = false;
var records = [];
var offset = 0;
var nextRotation = 0;
var logFileOpenFailWarn = false;
// buffer the write if a write is already in progress
// https://nodejs.org/api/fs.html#fs_fs_write_fd_data_position_encoding_callback
// "Note that it is unsafe to use fs.write multiple times on the same file without waiting for the callback."
const writeLogRecordToFile = function (record,cb) {
if (Date.now() > nextRotation) {
if ( !logFileOpenFailWarn ) {
rotation++;
if (logFileFd) {
fs.close(logFileFd);
}
logFilePath = _calculateLogFilePath(logDir, uid, rotation);
if (cluster.isMaster) {
if(!logToConsole) {
writeConsoleLog('log', {component: CONSOLE_LOG_TAG}, 'logging to ' + logFilePath);
}
}
}
try {
logFileFd = fs.openSync(logFilePath, 'a', 0o0600);
} catch (e) {
if ( !logFileOpenFailWarn ) {
writeConsoleLog('log',{component: CONSOLE_LOG_TAG}, 'Error in creating log file: %s, error: %s',logFilePath, e.message);
logFileOpenFailWarn = true;
}
writeLogRecordToConsole(record);
return record;
}
logFileOpenFailWarn = false;
nextRotation = Date.now() + ((logConfig.rotate_interval || 24) * 60 * 60 * 1000); // hours -> ms
}
if ( record ) records.push(record);
if ( writeInProgress || (records.length === 0) ) {
return record;
}
writeInProgress = true;
const buffer = records.join('');
records = [];
fs.write(logFileFd, buffer, offset, 'utf8', function (err, written) {
writeInProgress = false;
if (err) {
if (!logFailWarn) {
// print warning once, dumping every failure to console would overwhelm the console
writeConsoleLog('warn',{component: CONSOLE_LOG_TAG},'error writing log',err);
logFailWarn = true;
}
} else {
offset += written;
}
if (records.length > 0) {
process.nextTick(function () {
writeLogRecordToFile();
});
} else {
if ( cb !== undefined ) {
try {
cb();
} catch (e) {
writeConsoleLog('log',{component: CONSOLE_LOG_TAG},e);
}
}
}
});
return buffer;
}
const writeLogRecordToConsole = (record,cb) => {
if(record) {
if(record.startsWith('error') || record.startsWith('warn')) {
writeConsoleLog('error',{component: CONSOLE_LOG_TAG},record);
} else {
process.stdout.write(record);
if ( cb !== undefined ) {
try {
cb();
} catch (e) {
writeConsoleLog('log',{component: CONSOLE_LOG_TAG},e);
}
}
}
}
}
const writeLog = function (level, obj, msg, isTransactionLog) {
if (!cluster.isMaster) {
const rec = serializeLogRecord(level, logConfig.level, obj, msg, isTransactionLog, logConfig.stack_trace);
if (process.connected) {
process.send({level:level, msg: rec});
}
return rec;
}
return logger.writeLogRecord({msg:serializeLogRecord(level, logConfig.level, obj, msg, isTransactionLog, logConfig.stack_trace)});
}
logger = {
trace: function (obj, msg) {
return writeLog('trace', obj, msg);
},
debug: function (obj, msg) {
return writeLog('debug', obj, msg);
},
info: function (obj, msg) {
return writeLog('info', obj, msg);
},
warn: function (obj, msg) {
return writeLog('warn', obj, msg);
},
error: function (obj, msg) {
return writeLog('error', obj, msg);
},
eventLog: function (obj, msg) {
if ( obj.level ) {
return writeLog(obj.level, obj, msg, true);
} else {
return null;
}
},
consoleLog: function (level, obj, ...data) {
return writeConsoleLog(level, obj, ...data);
},
stats: function (statsInfo, msg) {
return writeLog('stats', { stats: statsInfo }, msg);
},
setLevel: function (level) {
logConfig.level = level;
},
writeLogRecord: function(record,cb) {
const writeRecordToOutput = logToConsole ? writeLogRecordToConsole : writeLogRecordToFile;
if ( record && record.msg ) writeRecordToOutput(record.msg,cb);
return record;
},
setTransactionContext: ( correlation_id,sourceRequest) => {
let clientIP = ( (sourceRequest.socket && sourceRequest.socket.remoteAddress) ? sourceRequest.socket.remoteAddress : '');
clientIP = clientIP ? clientIP.replace('::ffff:','') : '';
if ( !isValidIPaddress(clientIP) ) {
clientIP = '';
}
let targetPortStr = '';
if ( !isNaN(parseInt(sourceRequest.targetPort)) ) {
targetPortStr = ':'+ parseInt(sourceRequest.targetPort);
}
sourceRequest.transactionContextData = {
correlation_id: correlation_id,
method: sourceRequest.method,
url: sourceRequest.url,
host: (sourceRequest.headers ? sourceRequest.headers.host : ''),
clientId: (sourceRequest.headers ? sourceRequest.headers['x-api-key'] : ''),
remoteAddress: (sourceRequest.socket ? (sourceRequest.socket.remoteAddress + ':' + sourceRequest.socket.remotePort) : ':0'),
clientIP: clientIP,
targetHostName: sourceRequest.targetHostname + targetPortStr
}
}
};
if (cluster.isMaster) {
if(logToConsole) {
writeConsoleLog('log',{component: CONSOLE_LOG_TAG},'logging to console');
}
Object.keys(cluster.workers).forEach((id) => {
cluster.workers[id].on('message', function (msg) {
if ( msg && msg.msg ) logger.writeLogRecord(msg.msg);
});
});
}
return logger;
}
module.exports.getLogger = function () {
return logger;
}
const writeConsoleLog = function (level, obj, ...dataList) {
// uncomment the below condition to disable the blank console logs
if ( console[level] /*&& dataList && dataList.length > 0*/ ) {
const Timestamp = new Date().toISOString();
let ProcessId = '';
if (cluster.isMaster) {
ProcessId = process.pid;
} else if (cluster.isWorker) {
ProcessId = cluster.worker.id;
}
let component = '';
if (obj && obj.component ) {
component = obj.component;
}
let message = Timestamp + ' ['+ ProcessId + ']'+ ' ['+ component + ']';
console[level](message, util.format(...dataList));
}
}
module.exports.writeConsoleLog = writeConsoleLog;
// choose certain properties of req/res/err to include in log records, pass the rest through
// be extra careful to not throw an error here
// - by inadvertently dereferencing any null/undefined objects
function serializeLogRecord(level, configLevel, obj, text, isTransactionLog, stackTrace) {
if (configLevel === 'none') {
return null;
}
switch (level) {
case 'trace': {
if (configLevel === 'error' || configLevel === 'warn' || configLevel === 'info' || configLevel === 'debug') {
return null;
}
break;
}
case 'debug': {
if (configLevel === 'error' || configLevel === 'warn' || configLevel === 'info') {
return null;
}
break;
}
case 'info': {
if (configLevel === 'error' || configLevel === 'warn') {
return null;
}
break;
}
case 'warn': {
if ( configLevel === 'error' ) {
return null;
}
break;
}
}
const record = {};
let transactionContextData = {};
if (typeof obj === 'string') {
if (text) text = text + ' ' + obj; // append obj to text
else text = obj; // assign obj to text
} else if (obj) Object.keys(obj).forEach(function (key) {
if (key === 'req') {
const req = obj[key];
if (req) {
if ( req.transactionContextData ) {
transactionContextData = req.transactionContextData;
} else {
record.m = req.method;
record.u = req.url || req.path;
record.h = (req.headers ? req.headers.host : '');
if (!record.h && req.agent && req.agent.sockets) {
let socketdata = Object.keys(req.agent.sockets)[0];
if ( socketdata ) {
record.h = socketdata.replace(':',''); // used if req is target request object
}
}
}
}
} else if (key === 'res') {
const res = obj[key];
if (res) {
record.s = res.statusCode;
}
} else if (key === 'err') {
const err = obj[key];
if (err) {
record.name = err.name;
record.message = err.message;
record.code = err.code;
record.stack = err.stack;
}
} else if (key === 'stats') {
const stats = obj[key];
if (stats) {
Object.keys(stats).forEach(function (key) {
if (key === 'statusCodes') {
const codes = stats[key];
record[key] = '{' + Object.keys(codes).map(function (code) {
return code + '=' + codes[code];
}).join(', ') + '}'
} else {
record[key] = stats[key];
}
});
}
const mem = process.memoryUsage();
record.rss = mem.rss;
const cpus = os.cpus();
const userTimes = [];
cpus.forEach(function (cpu) {
userTimes.push(cpu.times.user);
});
record.cpu = '[' + userTimes.join(', ') + ']';
} else if (key === 'transactionContextData') {
transactionContextData = obj[key];
} {
record[key] = obj[key];
}
});
if (isTransactionLog) {
record.transactionContextData = transactionContextData;
return serializeEventLogRecord(level, record, text, stackTrace);
}
const preamble = new Date().toISOString() + ' ';
if ( level !== 'trace' && stackTrace !== true ) {
delete record.stack;
}
let ProcessId = '';
if (cluster.isMaster) {
ProcessId = process.pid;
} else if (cluster.isWorker) {
ProcessId = cluster.worker.id;
}
var message = preamble + level + ' '+ ProcessId + ' ' + (text ? text + ' ' : '') +
Object.keys(record).map(function (key) {
return key + '=' + record[key]; // assumes vaules are primitive, no recursion
}).join(', ') +
os.EOL;
return message;
}
function statsTimer(statsLogInterval) {
// periodically log stats, but not if idle (no new requests or responses)
if (typeof statsLogInterval === 'number' && statsLogInterval > 0) {
var lastRequests = 0;
var lastResponses = 0;
const logTimer = setInterval(function () {
const statsInfo = stats.getStats();
if (lastRequests !== statsInfo.requests && lastResponses !== statsInfo.responses) {
lastRequests = statsInfo.requests;
lastResponses = statsInfo.responses;
logger.stats(statsInfo);
}
}, statsLogInterval * 1000); // convert seconds to milliseconds
logTimer.unref(); // don't keep event loop alive just for logging stats
}
}
const _calculateLogFilePath = (logDir, uid, rotation) => {
const baseFileName = util.format('edgemicro-%s-%s-%d-api.log', os.hostname(), uid, rotation);
const logFilePath = path.join(logDir, baseFileName);
return logFilePath;
};
const isValidIPaddress = (ipaddress) =>
{
if (/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ipaddress))
{
return (true)
}
return (false)
}
const serializeEventLogRecord = (level, record, text, stackTrace) => {
const Timestamp = new Date().toISOString();
const hostname = record.h || record.transactionContextData.host || ''; // by deault print source request hostname, else print from corresponding req object
let ProcessId = '';
if (cluster.isMaster) {
ProcessId = process.pid;
} else if (cluster.isWorker) {
ProcessId = cluster.worker.id;
}
const Org = process.env.CurrentOrgName;
const Environment = process.env.CurrentEnvironmentName;
let url = record.transactionContextData.url; // by deault print source request url
const APIProxy = url ? url.replace('/','') : '';
let ClientIp = record.transactionContextData.ClientIp || '';
const ClientId = record.transactionContextData.clientId || '';
const component = record.component || '';
let reqMethod = record.m || record.transactionContextData.method || ''; // by deault print source request method, else print from corresponding req object
let respStatusCode = record.s || '';
let errMessage = record.message || '';
let errCode = record.code || '';
let customMessage = ( text && text !== undefined ) ? text : '';
let correlationId = record.transactionContextData.correlation_id || '';
let timeTaken = record.d || '';
let errorStack = record.stack || '';
let message = Timestamp + ' ['+ level + ']'
+ '['+ hostname +']'
+ '['+ ProcessId +']'
+ '['+ Org +']'
+ '['+ Environment +']'
+ '['+ APIProxy +']'
+ '['+ ClientIp +']'
+ '['+ ClientId +']'
+ '['+ correlationId +']'
+ '['+ component +']'
+ '['+ customMessage +']'
+ '['+ reqMethod +']'
+ '['+ respStatusCode +']'
+ '['+ errMessage +']'
+ '['+ errCode +']'
+ '['+ timeTaken +']'
+os.EOL;
if ( level === 'trace' || stackTrace === true ) {
message += errorStack + os.EOL;
}
return message;
}
module.exports._calculateLogFilePath = _calculateLogFilePath;