is it possible in angular to set the debug log level at runtime?

懵懂的女人 提交于 2021-02-07 06:09:31

问题


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


回答1:


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.




回答2:


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.




回答3:


The way I did it was by

  1. manually injecting $cookies into the config block, then
  2. using that as a reference within a service.
  3. referring to the service var in all read locations.

    'use strict';
    app
      .config(['$logProvider', function($logProvider ){
        var $cookies;
        angular.injector(['ngCookies']).invoke(['$cookies', function(_$cookies_) {
          $cookies = _$cookies_;
        }]);
        var _enabled = $cookies.debugMode;
        $logProvider.debugEnabled(_enabled);
      }])
      .factory('DebugSvc', ['$cookies', 'HttpMonitorSvc',function ($cookies, HttpMonitorSvc) {
      return  {
        httpMonitor: HttpMonitorSvc,
        debugMode: $cookies.debugMode || 'inactive',
        setDebugMode: function (mode) {
          var _logEnabled = $cookies.debugMode;
    
          switch( mode ) {
            case 'active':
              _logEnabled = true;
              break;
          }
          $cookies.debugMode = mode;
          this.debugMode = mode;
        }
      };
    }]);
    


来源:https://stackoverflow.com/questions/27322242/is-it-possible-in-angular-to-set-the-debug-log-level-at-runtime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!