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() |
Matteo Scandolo | 280dcd3 | 2016-05-16 09:59:38 -0700 | [diff] [blame] | 16 | let logFn = $delegate.log; |
| 17 | let infoFn = $delegate.info; |
| 18 | let warnFn = $delegate.warn; |
| 19 | let errorFn = $delegate.error; |
| 20 | let debugFn = $delegate.debug; |
Matteo Scandolo | 7bc39c4 | 2016-04-20 11:38:42 -0700 | [diff] [blame] | 21 | |
| 22 | // create the replacement function |
| 23 | const replacement = (fn) => { |
| 24 | return function(){ |
Matteo Scandolo | 280dcd3 | 2016-05-16 09:59:38 -0700 | [diff] [blame] | 25 | // console.log(`Is Log Enabled: ${isLogEnabled()}`) |
Matteo Scandolo | 7bc39c4 | 2016-04-20 11:38:42 -0700 | [diff] [blame] | 26 | if(!isLogEnabled()){ |
Matteo Scandolo | 280dcd3 | 2016-05-16 09:59:38 -0700 | [diff] [blame] | 27 | // console.log('logging is disabled'); |
Matteo Scandolo | 7bc39c4 | 2016-04-20 11:38:42 -0700 | [diff] [blame] | 28 | return; |
| 29 | } |
| 30 | let args = [].slice.call(arguments); |
| 31 | let now = new Date(); |
| 32 | |
| 33 | // Prepend timestamp |
| 34 | args[0] = `[${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}] ${args[0]}`; |
| 35 | |
Matteo Scandolo | 280dcd3 | 2016-05-16 09:59:38 -0700 | [diff] [blame] | 36 | // HACK awfull fix for angular mock implementation whithin jasmine test failing issue |
| 37 | if (typeof $delegate.reset === 'function' && !($delegate.debug.logs instanceof Array)) { |
| 38 | // if we are within the mock and did not reset yet, we call it to avoid issue |
| 39 | // console.log('mock log impl fix to avoid logs array not existing...'); |
| 40 | $delegate.reset(); |
| 41 | } |
| 42 | |
Matteo Scandolo | 7bc39c4 | 2016-04-20 11:38:42 -0700 | [diff] [blame] | 43 | // Call the original with the output prepended with formatted timestamp |
| 44 | fn.apply(null, args) |
| 45 | }; |
| 46 | }; |
| 47 | |
Matteo Scandolo | 280dcd3 | 2016-05-16 09:59:38 -0700 | [diff] [blame] | 48 | $delegate.info = replacement(infoFn); |
| 49 | $delegate.log = replacement(logFn); |
| 50 | $delegate.warn = replacement(warnFn); |
| 51 | $delegate.error = replacement(errorFn); |
| 52 | $delegate.debug = replacement(debugFn); |
Matteo Scandolo | 7bc39c4 | 2016-04-20 11:38:42 -0700 | [diff] [blame] | 53 | |
| 54 | return $delegate; |
| 55 | }]); |
| 56 | }]); |