Matteo Scandolo | 17bf824 | 2017-01-23 17:30:39 -0800 | [diff] [blame] | 1 | export default function XosLogDecorator($provide: ng.auto.IProvideService) { |
| 2 | $provide.decorator('$log', function($delegate: any) { |
| 3 | const isLogEnabled = () => { |
Matteo Scandolo | 1aee198 | 2017-02-17 08:33:23 -0800 | [diff] [blame] | 4 | // 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 Scandolo | 17bf824 | 2017-01-23 17:30:39 -0800 | [diff] [blame] | 7 | }; |
| 8 | // Save the original $log.debug() |
| 9 | let logFn = $delegate.log; |
| 10 | let infoFn = $delegate.info; |
| 11 | let warnFn = $delegate.warn; |
Matteo Scandolo | 4e87023 | 2017-01-30 13:43:05 -0800 | [diff] [blame] | 12 | // let errorFn = $delegate.error; |
Matteo Scandolo | 17bf824 | 2017-01-23 17:30:39 -0800 | [diff] [blame] | 13 | 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 Scandolo | 47860fe | 2017-02-02 12:05:55 -0800 | [diff] [blame] | 26 | args.unshift(`[${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}]`); |
Matteo Scandolo | 17bf824 | 2017-01-23 17:30:39 -0800 | [diff] [blame] | 27 | |
| 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 Scandolo | 4e87023 | 2017-01-30 13:43:05 -0800 | [diff] [blame] | 36 | // $delegate.error = replacement(errorFn); // note this will prevent errors to be printed |
Matteo Scandolo | 17bf824 | 2017-01-23 17:30:39 -0800 | [diff] [blame] | 37 | $delegate.debug = replacement(debugFn); |
| 38 | |
| 39 | return $delegate; |
| 40 | }); |
| 41 | } |