blob: c4543e2a10cf884dfd19eceb09b00ff6bdc0c6d6 [file] [log] [blame]
Matteo Scandolo17bf8242017-01-23 17:30:39 -08001export default function XosLogDecorator($provide: ng.auto.IProvideService) {
2 $provide.decorator('$log', function($delegate: any) {
3 const isLogEnabled = () => {
Matteo Scandolo1aee1982017-02-17 08:33:23 -08004 // NOTE to enable debug, in the broser console set: localStorage.debug = 'true'
5 // NOTE to disable debug, in the broser console set: localStorage.debug = 'false'
6 return window.localStorage.getItem('debug') === 'true';
Matteo Scandolo17bf8242017-01-23 17:30:39 -08007 };
8 // Save the original $log.debug()
9 let logFn = $delegate.log;
10 let infoFn = $delegate.info;
11 let warnFn = $delegate.warn;
Matteo Scandolo4e870232017-01-30 13:43:05 -080012 // let errorFn = $delegate.error;
Matteo Scandolo17bf8242017-01-23 17:30:39 -080013 let debugFn = $delegate.debug;
14
15 // create the replacement function
16 const replacement = (fn) => {
17 return function(){
18 if (!isLogEnabled()) {
19 return;
20 }
21
22 let args = [].slice.call(arguments);
23 let now = new Date();
24
25 // Prepend timestamp
Matteo Scandolo47860fe2017-02-02 12:05:55 -080026 args.unshift(`[${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}]`);
Matteo Scandolo17bf8242017-01-23 17:30:39 -080027
28 // Call the original with the output prepended with formatted timestamp
29 fn.apply(null, args);
30 };
31 };
32
33 $delegate.info = replacement(infoFn);
34 $delegate.log = replacement(logFn);
35 $delegate.warn = replacement(warnFn);
Matteo Scandolo4e870232017-01-30 13:43:05 -080036 // $delegate.error = replacement(errorFn); // note this will prevent errors to be printed
Matteo Scandolo17bf8242017-01-23 17:30:39 -080037 $delegate.debug = replacement(debugFn);
38
39 return $delegate;
40 });
41}