-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathangular-ny-logger.js
76 lines (74 loc) · 2.73 KB
/
angular-ny-logger.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
angular.module('ny.logger', []).provider('Logger', [function () {
var isEnabled = true;
this.enabled = function(_isEnabled) {
isEnabled = !!_isEnabled;
};
this.$get = ['$log', function($log) {
var Logger = function(context) {
this.context = context;
};
Logger.getInstance = function(context) {
return new Logger(context);
};
Logger.supplant = function(str, o) {
return str.replace(
/\{([^{}]*)\}/g,
function (a, b) {
var r = o[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
}
);
};
Logger.getFormattedTimestamp = function(date) {
return Logger.supplant('{0}:{1}:{2}:{3}', [
date.getHours(),
date.getMinutes(),
date.getSeconds(),
date.getMilliseconds()
]);
};
Logger.prototype = {
_log: function(originalFn, args) {
if (!isEnabled) {
return;
}
var now = Logger.getFormattedTimestamp(new Date());
var message = '', supplantData = [];
switch (args.length) {
case 1:
message = Logger.supplant("{0} - {1}: {2}", [ now, this.context, args[0] ]);
break;
case 3:
supplantData = args[2];
message = Logger.supplant("{0} - {1}::{2}(\'{3}\')", [ now, this.context, args[0], args[1] ]);
break;
case 2:
if (typeof args[1] === 'string') {
message = Logger.supplant("{0} - {1}::{2}(\'{3}\')", [ now, this.context, args[0], args[1] ]);
} else {
supplantData = args[1];
message = Logger.supplant("{0} - {1}: {2}", [ now, this.context, args[0] ]);
}
break;
}
$log[originalFn].call(null, Logger.supplant(message, supplantData));
},
log: function() {
this._log('log', arguments);
},
info: function() {
this._log('info', arguments);
},
warn: function() {
this._log('warn', arguments);
},
debug: function() {
this._log('debug', arguments);
},
error: function() {
this._log('error', arguments);
}
};
return Logger;
}];
}]);