blob: e6bd62101f8ee436522f628a6bb3732e2ed689e2 [file] [log] [blame]
Matteo Scandolo7bc39c42016-04-20 11:38:42 -07001// TODO write tests for log
2
Matteo Scandolob585d382016-06-15 14:53:33 -07003/* eslint-disable angular/ng_window_service*/
4
Matteo Scandolo7bc39c42016-04-20 11:38:42 -07005angular.module('xos.helpers')
6.config([ '$provide', function( $provide )
7{
8 // Use the `decorator` solution to substitute or attach behaviors to
9 // original service instance; @see angular-mocks for more examples....
10
11 $provide.decorator( '$log', [ '$delegate', function( $delegate )
12 {
13
14 const isLogEnabled = () => {
15 return window.location.href.indexOf('debug=true') >= 0;
Matteo Scandolob585d382016-06-15 14:53:33 -070016 };
Matteo Scandolo7bc39c42016-04-20 11:38:42 -070017 // Save the original $log.debug()
Matteo Scandolo280dcd32016-05-16 09:59:38 -070018 let logFn = $delegate.log;
19 let infoFn = $delegate.info;
20 let warnFn = $delegate.warn;
21 let errorFn = $delegate.error;
22 let debugFn = $delegate.debug;
Matteo Scandolo7bc39c42016-04-20 11:38:42 -070023
24 // create the replacement function
25 const replacement = (fn) => {
26 return function(){
Matteo Scandolo280dcd32016-05-16 09:59:38 -070027 // console.log(`Is Log Enabled: ${isLogEnabled()}`)
Matteo Scandolo7bc39c42016-04-20 11:38:42 -070028 if(!isLogEnabled()){
Matteo Scandolo280dcd32016-05-16 09:59:38 -070029 // console.log('logging is disabled');
Matteo Scandolo7bc39c42016-04-20 11:38:42 -070030 return;
31 }
32 let args = [].slice.call(arguments);
33 let now = new Date();
34
35 // Prepend timestamp
36 args[0] = `[${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}] ${args[0]}`;
37
Matteo Scandolo280dcd32016-05-16 09:59:38 -070038 // HACK awfull fix for angular mock implementation whithin jasmine test failing issue
Matteo Scandolob585d382016-06-15 14:53:33 -070039 if (angular.isFunction($delegate.reset) && !($delegate.debug.logs instanceof Array)) {
Matteo Scandolo280dcd32016-05-16 09:59:38 -070040 // if we are within the mock and did not reset yet, we call it to avoid issue
41 // console.log('mock log impl fix to avoid logs array not existing...');
42 $delegate.reset();
43 }
44
Matteo Scandolo7bc39c42016-04-20 11:38:42 -070045 // Call the original with the output prepended with formatted timestamp
46 fn.apply(null, args)
47 };
48 };
49
Matteo Scandolo280dcd32016-05-16 09:59:38 -070050 $delegate.info = replacement(infoFn);
51 $delegate.log = replacement(logFn);
52 $delegate.warn = replacement(warnFn);
53 $delegate.error = replacement(errorFn);
54 $delegate.debug = replacement(debugFn);
Matteo Scandolo7bc39c42016-04-20 11:38:42 -070055
56 return $delegate;
57 }]);
58}]);