Is it possible to switch the $logProvider.debugEnabled([flag]);
at runtime?
The current situation:
The angular client load settings from the server at the run phase. Depends on the settings I would like to set the method $logProvider.debugEnabled([flag])
.
Thanks in advance, Stevo
The short answer for this is: no, not really.
Once your application hass been configured through your .config()
block, no further configuration can take place after the application has bootstrapped.
This is due to the way providers work; they're only available at configuration time. There might be a way to force the configuration, and then manually re-inject the new $log
service into all of your controllers, but if there is a way to do that, I'm not sure how.
I've decorated $log.debug(...)
to change the loglevel at runtime.
Looking at Enhancing AngularJS Logging using Decorators, I got the idea for the following code snippet:
(function () {
var KEY = "debugEnabled";
angular.module("service.config", [])
.config(function ($provide, $logProvider) {
// AngularJS has debug enabled by default, but just to be sure...
$logProvider.debugEnabled(true);
// Disabling localStorageDebug (if not set)
if (localStorage.getItem(KEY) === null) {
localStorage.setItem(KEY, "false");
}
// add a check for localStorageDebug before actually calling $log.debug(...)
$provide.decorator('$log', function ($delegate) {
var debugFunction = $delegate.debug;
$delegate.debug = function () {
if (localStorage.getItem(KEY) !== "false") {
debugFunction.apply(undefined, arguments)
}
};
return $delegate;
});
})
.service("ConfigService", function ($log) {
this.debugEnabled = function (flag) {
$log.info("Setting debugEnabled to " + flag);
localStorage.setItem(KEY, flag.toString());
}
});
})();
// exposing ConfigService to global scope (be aware of possible clashes!),
// therefore making it easily accessible from the console
var cfg;
window.onload = function () {
cfg = angular.element(document.body).injector().get("ConfigService");
};
The decorator only forwards calls to $log.debug
if debugEnabled
is set to true
in your local storage - the value can be changed through the ConfigService
service.
Now you can just call ConfigService#debugEnabled
with the value you've loaded from your server to change the loglevel.
Thanks to the last four lines, you can also simply call cfg.debugEnabled(true)
on your console to enable debug mode at runtime.
If you don't like to type into the console, you could avoid the global cfg
and use javascript bookmarks (or elements on your website) to change the log level.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With