Matteo Scandolo | 7bc39c4 | 2016-04-20 11:38:42 -0700 | [diff] [blame] | 1 | // TODO write tests for log |
| 2 | |
| 3 | angular.module('xos.helpers') |
| 4 | .config([ '$provide', function( $provide ) |
| 5 | { |
| 6 | // Use the `decorator` solution to substitute or attach behaviors to |
| 7 | // original service instance; @see angular-mocks for more examples.... |
| 8 | |
| 9 | $provide.decorator( '$log', [ '$delegate', function( $delegate ) |
| 10 | { |
| 11 | |
| 12 | const isLogEnabled = () => { |
| 13 | return window.location.href.indexOf('debug=true') >= 0; |
| 14 | } |
| 15 | // Save the original $log.debug() |
| 16 | let debugFn = $delegate.info; |
| 17 | |
| 18 | // create the replacement function |
| 19 | const replacement = (fn) => { |
| 20 | return function(){ |
| 21 | if(!isLogEnabled()){ |
| 22 | console.log('logging is disabled'); |
| 23 | return; |
| 24 | } |
| 25 | let args = [].slice.call(arguments); |
| 26 | let now = new Date(); |
| 27 | |
| 28 | // Prepend timestamp |
| 29 | args[0] = `[${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}] ${args[0]}`; |
| 30 | |
| 31 | // Call the original with the output prepended with formatted timestamp |
| 32 | fn.apply(null, args) |
| 33 | }; |
| 34 | }; |
| 35 | |
| 36 | $delegate.info = replacement(debugFn); |
| 37 | |
| 38 | return $delegate; |
| 39 | }]); |
| 40 | }]); |