AngularJS : using the integrated AngularJS $log service with decorator
AngularJS : using the integrated AngularJS $log service with decorator
HTML
<div ng-app="app" ng-controller="LogController as vm">
<strong>Make sure to open a javascript console so you can see the output.</strong>
<br/>
<br/>
<button style="background: #2196f3; color: white; border: 0; padding: 10px 20px; margin-bottom: 5px;display:block;" ng-click="vm.doLog('debug')">
Log
<STRONG>DEBUG</STRONG>
</button>
<button style="background: #607d8b; color: white; border: 0; padding: 10px 20px; margin-bottom: 5px;display:block;" ng-click="vm.doLog('info')">
Log
<STRONG>INFO</STRONG>
</button>
<button style="background: #ff9800; color: white; border: 0; padding: 10px 20px; margin-bottom: 5px;display:block;" ng-click="vm.doLog('warn')">
Log
<STRONG>WARN</STRONG>
</button>
<button style="background: #ff5722; color: white; border: 0; padding: 10px 20px; margin-bottom: 5px;display:block;" ng-click="vm.doLog('error')">
Log
<STRONG>ERROR</STRONG>
</button>
<button style="background: #ff5722; color: white; border: 0; padding: 10px 20px; margin-bottom: 5px;display:block;" ng-click="vm.doLogErrorObject()">
Log
<STRONG>ERROR OBJECT</STRONG>
</button>
<button style="background: #8bc34a; color: white; border: 0; padding: 10px 20px; margin-bottom: 5px;display:block;" ng-click="vm.doLog('log')">
normal
<STRONG>LOG</STRONG>
</button>
</div>
JavaScript
angular
.module('app', [])
.controller('LogController', LogController)
.constant('debugEnabled', true) // change to TRUE | FALSE to enable or disable $log
.config(function($logProvider, $provide) {
// decorate $log
$provide.decorator('$log', function($delegate, debugEnabled) {
// check delegate method
$delegate.debug = debugEnabled ? $delegate.debug : function() { alert('$log disabled'); };
$delegate.info = debugEnabled ? $delegate.info : function() { alert('$log disabled'); };
$delegate.warn = debugEnabled ? $delegate.warn : function() { alert('$log disabled'); };
$delegate.error = debugEnabled ? $delegate.error : function() { alert('$log disabled'); };
$delegate.log = debugEnabled ? $delegate.log : function() { alert('$log disabled'); };
// return delegate
return $delegate;
});
});
function LogController($log, debugEnabled) {
var vm = this;
vm.doLog = function(type) {
switch (type) {
case "debug":
$log.debug("Some debug");
break;
case "info":
$log.info("Some debug");
break;
case "warn":
$log.warn("Some debug");
break;
case "error":
$log.error("Some debug");
break;
case "log":
default:
$log.log("Some debug");
break;
}
}
vm.doLogErrorObject = function() {
$log.error(new Error('$log service error'));
}
}