-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtechLogger.js
298 lines (262 loc) · 7.99 KB
/
techLogger.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
/**
* Our Logger that wrap Winston logging library.
*/
const _ = require('lodash');
const path = require('path');
const splash = require('./lib/splash');
const stringify = require('json-stringify-safe');
const typeOf = require('typeof--');
const winston = require('winston');
let configurationDate;
let consologger;
let filogger;
let syslogger;
let syslogOptions;
const LOG_LEVELS = ['emerg', 'alert', 'crit', 'error', 'notice', 'warn', 'info', 'debug'];
// Winston levels correctly ordered
// DO NOT TRUST Winston level definition as it does not comply to a "logical" threshold mechanism
const LEVELS_CONFIG = {
levels: {
emerg: 7,
alert: 6,
crit: 5,
error: 4,
warn: 3,
notice: 2,
info: 1,
debug: 0
},
colors: {
emerg: 'magenta',
alert: 'magenta',
crit: 'red',
error: 'red',
warn: 'yellow',
notice: 'green',
info: 'blue',
debug: 'cyan'
}
};
// Make winston aware of these colors
winston.addColors(LEVELS_CONFIG.colors);
function _makeLogger(prefix = _getCallerFile()) {
const logPrefix = `[${prefix}]`;
let logger = {
/**
* Setup the logger configuration
* @param {Object} config See below for details
* @param {Object} config.console Console configuration (optional)
* @param {Object} config.console.thresholdLevel Minimum level of messages that the logger should log. Default is info.
* @param {Object} config.syslog Syslog configuration (optional)
* @param {Object} config.syslog.host The host running syslogd.
* @param {Object} config.syslog.appName The name of the application.
* @param {Object} config.syslog.thresholdLevel Minimum level of messages that the logger should log. Default is info.
* @param {Object} config.file File configuration (optional)
* @param {Object} config.file.name The filename of the logfile to write.
* @param {Object} config.file.maxSize Max size in bytes of the logfile, if the size is exceeded then a new file is created.
* @param {Object} config.file.maxNumber Limit the number of files created when the size of the logfile is exceeded.
* @param {Object} config.file.json If true, messages will be logged as JSON. Default is false.
* @param {Object} config.file.thresholdLevel Minimum level of messages that the logger should log. Default is info.
*
* @return {boolean} True if the configuration has changed, otherwise false.
*/
setup(config) {
var currentCfg = _getLoggerConfig();
var updated = !currentCfg || !_.isEqual(currentCfg.config, config);
if (updated) {
_setLoggerConfig(config);
}
return updated;
},
createExpressLoggerStream(level) {
return { write: (message /*, encoding */) => _log(level, message) };
},
splash(app, configuration) {
splash(this, app, configuration);
}
};
// Initialize all logger levels methods
LOG_LEVELS.forEach(level => {
logger[level] = (...args) => _log(level, _prefixLog(args, logPrefix));
});
return logger;
}
function _prefixLog(log, logPrefix) {
var prefixedLog = log;
prefixedLog.unshift(logPrefix);
return prefixedLog;
}
/**
* Log the message using winston or console
*
* @param {Object} log
* {String] log.level
* {String} log.message
*/
function _doLog(log) {
if (consologger) {
consologger.log(log.level, log.message);
}
if (filogger) {
filogger.log(log.level, log.message);
}
if (syslogger) {
syslogger.log(log.level, syslogOptions.appName, log.message);
}
}
/**
* Log a message with the specified level
*
* @param {String} level the level
* @param {Array} log list of message parts
*/
function _log(level, log) {
const toString = object => {
return stringify(object, (key, value) => {
// Do not process inner objects with a type named xxxStream
if (typeOf(value).indexOf('Stream') !== -1) {
return '[Stream ~]';
}
return value;
});
};
var message = log
.map(element => {
if (element instanceof Error) {
return element.stack;
} else if (typeof element !== 'string') {
return toString(element);
} else {
return element;
}
})
.join(' ');
if (!configurationDate || configurationDate < _getLoggerConfig().date) {
// Logger needs to be configured
_configureLogger();
}
_doLog({ level, message });
}
/**
* Returns the configuration of the logger
*
* @return {Object} the configuration of the logger
*/
function _getLoggerConfig() {
return global.NODE_TECH_LOGGER_CFG;
}
/**
* Set the configuration of the logger
*
* @param {Object} config the logger configuration
*/
function _setLoggerConfig(config) {
global.NODE_TECH_LOGGER_CFG = {
date: new Date().getTime(),
config
};
}
/**
* Initialize winston logger
*/
function _configureLogger() {
var loggerConfig = _getLoggerConfig();
if (!loggerConfig) {
// Default config
_setLoggerConfig({});
loggerConfig = _getLoggerConfig();
var msg = '\n\n!!! =========================================== !!!';
msg += '\n!!! No configuration set for node-tech-logger !!!';
msg += '\n!!! =========================================== !!!\n\n';
console.warn(msg);
}
// Keep the date of the last applied configuration
configurationDate = loggerConfig.date;
var config = loggerConfig.config;
_configureConsoleLogger(config);
_configureFileLogger(config);
_configureSyslogLogger(config);
}
/**
* Configure console logger
*/
function _configureConsoleLogger(config) {
if (consologger) {
consologger.remove(winston.transports.Console);
} else {
consologger = new winston.Logger({});
consologger.setLevels(LEVELS_CONFIG.levels);
}
consologger.add(winston.transports.Console, {
colorize: true,
level: (config.console && config.console.thresholdLevel) || 'info'
});
}
/**
* Configure file logger
*/
function _configureFileLogger(config) {
filogger = null;
if (config.file) {
filogger = new winston.Logger({
transports: [
new winston.transports.File({
filename: config.file.name,
maxsize: config.file.maxSize,
maxFiles: config.file.maxNumber,
json: config.file.json || false,
level: config.file.thresholdLevel || 'info'
})
]
});
filogger.setLevels(LEVELS_CONFIG.levels);
}
}
/**
* Configure syslog logger
*/
function _configureSyslogLogger(config) {
syslogger = null;
if (config.syslog) {
syslogOptions = config.syslog;
require('winston-syslog');
// syslog options
var options = {
host: config.syslog.host,
port: 514,
protocol: 'udp4',
app_name: config.syslog.appName,
facility: 'local0',
level: config.syslog.thresholdLevel || 'info'
};
syslogger = new winston.Logger({
colors: winston.config.syslog.colors,
transports: [new winston.transports.Syslog(options)]
});
syslogger.setLevels(LEVELS_CONFIG.levels);
}
}
/**
* Compute caller file name to use it as prefix
*/
function _getCallerFile() {
var originalFunc = Error.prepareStackTrace;
function shouldSkipFile(filename) {
return _.endsWith(currentfile, 'techLogger.js') || currentfile === 'module.js' || currentfile === 'node.js';
}
var callerfile;
try {
var err = new Error();
var currentfile;
Error.prepareStackTrace = (err, stack) => stack;
currentfile = err.stack.shift().getFileName();
while (err.stack.length && shouldSkipFile(currentfile)) {
currentfile = err.stack.shift().getFileName();
}
callerfile = currentfile;
} catch (e) {}
Error.prepareStackTrace = originalFunc;
return callerfile ? callerfile.split(path.sep).pop() : callerfile;
}
var defaultLogger = _makeLogger();
module.exports = _.assignIn(_makeLogger, defaultLogger);