-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
275 lines (226 loc) · 6.09 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
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
/**
* Console Enhancer
* Provides new features to console, such as styling, source information (file and line number) and level-based filtering
*
* @author Martin Moscovich ([email protected])
* Copyright (c) 2013 NaN Labs (www.nan-labs.com)
*/
var fs = require('fs');
var path = require('path');
var util = require("util");
var moment = require('moment');
/**
* ERROR LEVELS.
* Higher Levels include the lower levels.
*/
var levels = {
ERROR: 0,
WARN: 1,
INFO: 2,
DEBUG: 3,
TRACE: 4,
ALL: 5
};
/**
* Font styles
*/
var styles = {
CLEAR: 0,
BOLD: 1,
ITALIC: 3,
UNDERLINE: 4
};
/**
* Font colors
*/
var colors = {
RED: 31,
YELLOW: 33,
WHITE: 37,
BLACK: 30
};
/**
* Definitions of styles and colors for each level
*/
var levelStyles = {
ERROR: [styles.BOLD, colors.RED],
WARN: [styles.BOLD, colors.YELLOW],
INFO: [styles.BOLD, colors.WHITE],
DEBUG: [colors.WHITE],
TRACE: [styles.BOLD, colors.BLACK]
};
/**
* Current level set
*/
var currentLevel = levels.ALL;
/**
* Flag that decides if colors/styling is used in the output
*/
var useStyling = true;
/**
* Flag indicating whether to show the file name and line on each log.
* Currently, it is always true except when level is ERROR
* (to improve performance and because the error's stack contains the line number)
*/
var showSourceInfo = true;
/**
* Array of functions used to write the logs.
* By default, only console logger is used
*/
var appenders = [logToConsole];
/**
* Path of the log file.
*/
var currentFilePath = './logs/server.log';
/**
* Reference to the original console.error in case of failure
*/
var originalConsoleError = global.console.error;
/**
* Flag that indicates if the timestamp should be shown in the log.
*/
var includeDate = false;
/**
* Function to call in order to improve node's console.
* @param options configuration options
*/
exports.enhance = function(options) {
var level = options.level;
if(options.file) initFileLogger(options.filepath);
if(level === 'VERBOSE') level = 'TRACE';
if (options.includeDate) includeDate = options.includeDate;
var levelNumber = levels[level];
if (typeof levelNumber !== 'undefined') currentLevel = levelNumber;
showSourceInfo = (options.showSourceInfo !== undefined) ? options.showSourceInfo : (currentLevel !== 0);
useStyling = (options.useStyling !== undefined) ? options.useStyling === true : true;
global.console.info = LogBuilder.createLogger("INFO");
global.console.warn = LogBuilder.createLogger("WARN");
global.console.debug = LogBuilder.createLogger("DEBUG");
global.console.verbose = LogBuilder.createLogger("TRACE");
global.console.error = LogBuilder.createErrorLogger();
global.console.log = global.console.debug;
};
/**
* Initialzes the file logger
* @param filepath path to the log file
*/
function initFileLogger(filepath) {
currentFilePath = filepath || currentFilePath;
var logDir = path.dirname(currentFilePath);
appenders.push(logToFile);
if(!fs.existsSync(logDir)) fs.mkdirSync(logDir);
};
/**
* Writes the log to stderr
*
* Partially based on clim (http://github.com/epeli/node-clim)
* Copyright (c) 2009-2011 Esa-Matti Suuronen <[email protected]>
*/
function writeLog(level, msg) {
var line;
if(showSourceInfo) {
var si = getSourceInfo();
if (includeDate) {
line = util.format("[%s] <%s>\t[%s:%s] %s", moment().format(), level, si.file, si.lineNumber, msg);
} else {
line = util.format("<%s>\t[%s:%s] %s", level, si.file, si.lineNumber, msg);
}
} else {
if (includeDate) {
line = util.format("[%s] <%s>\t%s", moment().format(), level, msg);
} else {
line = util.format("<%s>\t%s", level, msg);
}
}
line += '\n';
appenders.forEach(function(appender) {
appender(level, line);
});
}
function logToConsole(level, line) {
if (useStyling){
line = logStyler.addCodes(line, levelStyles[level]);
}
process.stderr.write(line);
};
function logToFile(level, line) {
fs.appendFile(currentFilePath, line, function (err) {
if (err) {
originalConsoleError("Error logging to '" + currentFilePath + "':\n" + err);
throw err;
}
});
};
/**
* Gets the source information from the line being log
*/
function getSourceInfo() {
var exec = getStack()[3];
var pos = exec.getFileName().lastIndexOf('\\');
if(pos < 0) exec.getFileName().lastIndexOf('/');
return {
methodName: exec.getFunctionName() || 'anonymous',
file: exec.getFileName().substring(pos + 1),
lineNumber: exec.getLineNumber()
};
}
/**
* Gets the current stack in order to retrieve source code info.
*
* Based on Callsite (http://github.com/visionmedia/callsite)
* Copyright (c) 2011, 2013 TJ Holowaychuk <[email protected]>
*/
function getStack() {
var old = Error.stackTraceLimit;
Error.stackTraceLimit = 4;
var orig = Error.prepareStackTrace;
Error.prepareStackTrace = function(_, stack){ return stack; };
var err = new Error;
Error.captureStackTrace(err, arguments.callee);
var stack = err.stack;
Error.prepareStackTrace = orig;
Error.stackTraceLimit = old;
return stack;
}
/**
* Creates the loggers
*/
var LogBuilder = {
createLogger: function(level) {
return function () {
if(levels[level] <= currentLevel) {
var msg = util.format.apply(this, arguments);
writeLog(level, msg);
}
};
},
createErrorLogger: function() {
var level = "ERROR";
return function () {
if(levels[level] <= currentLevel) {
if(arguments[0] instanceof Error) {
arguments[0] = arguments[0].stack;
} else if(arguments[1] instanceof Error) {
arguments = [arguments[0] + ":\n" + arguments[1].stack];
}
var msg = util.format.apply(this, arguments);
writeLog(level, msg);
}
};
}
}
/**
* Adds the styles to the console logs
*/
var logStyler = {
getAnsi: function(style) {
return '\u001b['+style+'m';
},
addCodes: function(msg, codes) {
codes.forEach(function(c) {
msg = logStyler.getAnsi(c) + msg;
});
msg = msg + logStyler.getAnsi(styles.CLEAR);
return msg;
}
}