/
ConsoleAppender.js
120 lines (98 loc) · 3.43 KB
/
ConsoleAppender.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
/*
* Copyright 2011 eBay Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
function getConsole() {
if (typeof console === 'undefined') {
// probably IE and Developer Tools are not open
return null;
}
if (!console.log.apply || !console.log.call) {
// not a real log (for old IE versions)
return null;
}
return console;
}
var _console = getConsole();
var _noop = _console ? null : function() {};
function getStackTrace(error) {
var stacktraces = require('raptor-stacktraces');
return (stacktraces && stacktraces.trace) ? stacktraces.trace(error) : (error || '');
}
function ConsoleAppender() {
}
ConsoleAppender.prototype = {
/**
* Log statements for all levels pass through this method.
*/
log: _console ? function(logEvent) {
var logLevel = logEvent.logLevel;
var logFn = _console[logLevel.methodName] || _console.log;
if (!logFn) {
return;
}
try {
var args = logEvent.args.slice(0);
var len = args.length;
var error;
for (var i=0; i<len-1; i++) {
var arg = args[i];
if (arg instanceof Error) {
args[i] = getStackTrace(arg);
}
}
var lastArg = args[len-1];
if (lastArg instanceof Error) {
error = lastArg;
args[len-1] = '';
}
var logArgs = [logLevel.name + ' ' + logEvent.getLoggerName() + ':'].concat(args);
// log the message at the level specified
logFn.apply(_console, logArgs);
if (error) {
logFn.call(_console, error.stack || error.toString());
var cause = error._cause;
while (cause) {
logFn.call(_console, 'Caused by:');
logFn.call(_console, cause.stack || cause.toString());
cause = cause._cause;
}
}
if (logLevel.level === 0) {
if (_console.trace) {
_console.trace();
} else {
var stackTrace = getStackTrace();
if (stackTrace && _console.log) {
_console.log(stackTrace);
}
}
}
} catch (e) {
logFn = _console.error || logFn;
logFn.call(_console, e);
}
} : _noop,
/**
* Log the contents of the given object at the DEBUG level.
*/
dump: _console ? function(obj, desc) {
if (console.debug) {
console.log((desc ? 'DUMP ' + desc : 'DUMP') + ':');
console.debug(obj);
}
} : _noop
};
module.exports = ConsoleAppender;