forked from detro/consoleplusplus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconsole++.js
executable file
·333 lines (298 loc) · 9.6 KB
/
console++.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
/*
This file is part of the Console++ by Ivan De Marino <http://ivandemarino.me>.
Copyright (c) 2012, Ivan De Marino <http://ivandemarino.me>
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
if (console.LEVELS) {
// Already loaded. No need to manipulate the "console" further.
// NOTE: NodeJS already caches modules. This is just defensive coding.
exports = console;
return;
}
// private:
var _ANSICODES = {
'reset' : '\033[0m',
'bold' : '\033[1m',
'italic' : '\033[3m',
'underline' : '\033[4m',
'blink' : '\033[5m',
'black' : '\033[30m',
'red' : '\033[31m',
'green' : '\033[32m',
'yellow' : '\033[33m',
'blue' : '\033[34m',
'magenta' : '\033[35m',
'cyan' : '\033[36m',
'white' : '\033[37m'
},
_LEVELS = {
NONE : 0,
OFF : 0, //< alias for "NONE"
ERROR : 1,
WARN : 2,
WARNING : 2, //< alias for "WARN"
INFO : 3,
INFORMATION : 3, //< alias for "INFO"
DEBUG : 4
},
_LEVELS_COLOR = [ //< _LEVELS_COLOR position matches the _LEVELS values
"NOCOLOR",
"red",
"yellow",
"cyan",
"green"
],
_LEVELS_NAME = [ //< _LEVELS_NAME position matches the _LEVELS values
"NONE",
"ERROR",
"WARN ",
"INFO ",
"DEBUG"
],
_console = {
error : console.error,
warn : console.warn,
info : console.info,
debug : console.log,
log : console.log
},
_level = _LEVELS.DEBUG,
_colored = true,
_messageColored = false,
_timed = true,
_json = false,
_onOutput = null;
/**
* Take a string and apply console ANSI colors for expressions "#color{msg}"
* NOTE: Does nothing if "console.colored === false".
*
* @param str Input String
* @returns Same string but with colors applied
*/
var _applyColors = function(str) {
var tag = /#([a-z]+)\{|\}/,
cstack = [],
matches = null,
orig = null,
name = null,
code = null;
while (tag.test(str)) {
matches = tag.exec(str);
orig = matches[0];
if (console.isColored()) {
if (orig === '}') {
cstack.pop();
} else {
name = matches[1];
if (name in _ANSICODES) {
code = _ANSICODES[name];
cstack.push(code);
}
}
str = str.replace(orig, _ANSICODES.reset + cstack.join(''));
} else {
str = str.replace(orig, '');
}
}
return str;
};
/**
* Decorate the Arguments passed to the console methods we override.
* First element, the message, is now colored, timed and more (based on config).
*
* @param argsArray Array of arguments to decorate
* @param level Logging level to apply (regulates coloring and text)
* @returns Array of Arguments, decorated.
*/
var _decorateArgs = function(argsArray, level) {
var args = Array.prototype.slice.call(argsArray),
msg = argsArray[0],
levelMsg;
if (console.isJSONOutput()) {
var obj = {},
c = 1;
obj.level = console.getLevelName(level);
obj["@timestamp"] = new Date();
args.forEach(function(prop){
if(prop instanceof Error) {
obj["arg" + c] = prop.toString();
obj["stack"] = prop.stack;
obj["type"] = prop.type;
obj["arguments"] = prop.arguments;
}
else {
obj["arg" + c] = prop;
}
c++;
});
return [JSON.stringify(obj)];
}
else if (console.isColored()) {
levelMsg = _applyColors("#" + console.getLevelColor(level) + "{" + console.getLevelName(level) + "}");
msg = _applyColors(msg);
if (console.isMessageColored()) {
msg = _applyColors("#" + console.getLevelColor(level) + "{" + msg + "}");
}
} else {
levelMsg = console.getLevelName(level);
}
msg = _formatMessage(msg, levelMsg);
args.splice(0, 1, msg);
return args;
};
/**
* Formats the Message content.
* @param msg The message itself
* @param levelMsg The portion of message that contains the Level (maybe colored)
* @retuns The formatted message
*/
var _formatMessage = function(msg, levelMsg) {
if (console.isTimestamped()) {
return "[" + levelMsg + " - " + new Date().toJSON() + "] " + msg;
} else {
return "[" + levelMsg + "] " + msg;
}
};
/**
* Invokes the "console.onOutput()" callback, if it was set by user.
* This is useful in case the user wants to write the console output to another media as well.
*
* The callback is invoked with 2 parameters:
* - formattedMessage: formatted message, ready for output
* - levelName: the name of the logging level, to inform the user
*
* @param msg The Message itself
* @param level The Message Level (Number)
*/
var _invokeOnOutput = function(msg, level) {
var formattedMessage,
levelName;
if (_onOutput !== null && typeof(_onOutput) === "function") {
levelName = console.getLevelName(level);
formattedMessage = _formatMessage(msg, levelName);
_onOutput.call(null, formattedMessage, levelName);
}
};
// public:
// CONSTANT: Logging Levels
console.LEVELS = _LEVELS;
// Set/Get Level
console.setLevel = function(level) {
_level = level;
};
console.getLevel = function() {
return _level;
};
console.getLevelName = function(level) {
return _LEVELS_NAME[typeof(level) === "undefined" ? _level : level];
};
console.getLevelColor = function(level) {
return _LEVELS_COLOR[typeof(level) === "undefined" ? _level : level];
};
console.isLevelVisible = function(levelToCompare) {
return _level >= levelToCompare;
};
// Enable/Disable Colored Output
console.enableColor = function() {
_colored = true;
};
console.disableColor = function() {
_colored = false;
};
console.isColored = function() {
return _colored;
};
// Enable/Disable Colored Message Output
console.enableMessageColor = function() {
_messageColored = true;
};
console.disableMessageColor = function() {
_messageColored = false;
};
console.isMessageColored = function() {
return _messageColored;
};
// Enable/Disable Timestamped Output
console.enableTimestamp = function() {
_timed = true;
};
console.disableTimestamp = function() {
_timed = false;
};
console.isTimestamped = function() {
return _timed;
};
// Enable/Disable JSON Output
console.enableJSONOutput = function() {
_json = true;
};
console.disableJSONOutput = function() {
_json = false;
};
console.isJSONOutput = function() {
return _json;
};
// Set OnOutput Callback (useful to write to file or something)
// Callback: `function(formattedMessage, levelName)`
console.onOutput = function(callback) {
_onOutput = callback;
};
// Decodes coloring markup in string
console.str2clr = function(str) {
return console.isColored() ? _applyColors(str): str;
};
// Overrides some key "console" Object methods
console.error = function(msg) {
if (arguments.length > 0 && this.isLevelVisible(_LEVELS.ERROR)) {
_console.error.apply(this, _decorateArgs(arguments, _LEVELS.ERROR));
_invokeOnOutput(msg, _LEVELS.ERROR);
}
};
console.warn = function(msg) {
if (arguments.length > 0 && this.isLevelVisible(_LEVELS.WARN)) {
_console.warn.apply(this, _decorateArgs(arguments, _LEVELS.WARN));
_invokeOnOutput(msg, _LEVELS.WARN);
}
};
console.info = function(msg) {
if (arguments.length > 0 && this.isLevelVisible(_LEVELS.INFO)) {
_console.info.apply(this, _decorateArgs(arguments, _LEVELS.INFO));
_invokeOnOutput(msg, _LEVELS.INFO);
}
};
console.debug = function(msg) {
if (arguments.length > 0 && this.isLevelVisible(_LEVELS.DEBUG)) {
_console.debug.apply(this, _decorateArgs(arguments, _LEVELS.DEBUG));
_invokeOnOutput(msg, _LEVELS.DEBUG);
}
};
console.log = function(msg) {
if (arguments.length > 0) {
_console.log.apply(this, arguments);
}
};
console.logObject = function(obj) {
if (arguments.length === 1) {
obj["@timestamp"] = obj["@timestamp"] || new Date();
obj.level = obj.level || "NONE";
_console.log.apply(this, [JSON.stringify(obj)]);
}
};
exports = console;