blob: b8c5297d6a5ebedb8581929b598c7c73b64ed467 [file] [log] [blame]
Matteo Scandolo7bc39c42016-04-20 11:38:42 -07001// TODO write tests for log
2
3angular.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 Scandolo280dcd32016-05-16 09:59:38 -070016 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 Scandolo7bc39c42016-04-20 11:38:42 -070021
22 // create the replacement function
23 const replacement = (fn) => {
24 return function(){
Matteo Scandolo280dcd32016-05-16 09:59:38 -070025 // console.log(`Is Log Enabled: ${isLogEnabled()}`)
Matteo Scandolo7bc39c42016-04-20 11:38:42 -070026 if(!isLogEnabled()){
Matteo Scandolo280dcd32016-05-16 09:59:38 -070027 // console.log('logging is disabled');
Matteo Scandolo7bc39c42016-04-20 11:38:42 -070028 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 Scandolo280dcd32016-05-16 09:59:38 -070036 // 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 Scandolo7bc39c42016-04-20 11:38:42 -070043 // Call the original with the output prepended with formatted timestamp
44 fn.apply(null, args)
45 };
46 };
47
Matteo Scandolo280dcd32016-05-16 09:59:38 -070048 $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 Scandolo7bc39c42016-04-20 11:38:42 -070053
54 return $delegate;
55 }]);
56}]);