16 Apr

Using the AngularJS $logProvider

Logging and debugging is a daily occurrence when developing JavaScript based applications. AngularJS provides a simple, effective way to enable logging in your applications – the $logProvider. $logProvider is used to enable logging and the $log object is used to log within your applications objects.

Enabling

Enabling the $logProvider is as simple as injecting the $log object into your object and then calling $log.debug(); to send logs to the console.
Example:

Turning off logging

You can disable logging (AngularJS 1.1.2+) by calling
$logProvider.debugEnabled(false);
Example:

Extending

AngularJS provides a mechanisms to extend the built in $logProvider, $provider.decorator(). An example will get the point across much more quickly than me trying to explain it all.
Example:

Basically we intercept the call using decorate so we can add on the features and functionality we need to the $log.debug() call.

AngualrJS version 1.2.16 was used as a basis for this article.
Thanks to Burleson Thomas and this post for the extension example.

Share this

Comments (4)

Thyago Weber
September 10, 2015 Reply

Is it possible to set "debugEnabled" at runtime, let's say, using the devtools and setting it?

    John G. Gainfort, Jr.
    September 10, 2015 Reply

    Hi Thyago,

    To set the debugEnabled to true at runtime using devtools you can put a breakpoint on the $logProvide.debugEnabled(false) line then change the value to true then press ctrl + s (cmd + s for mac). This will then save the value as true during the rest of your session. If you refresh the page the value would be changed back to its value set in the code base.

    I tested this using Chrome devtools. I am unsure about other debug tools.

    Another option that would be more complicated would be to create build scripts that would set a config flag to a value designated by the type of build you are performing (dev or prod) than using a service to return that config flag setting into the application and setting the debugEnabled according to that value.

      Thyago Weber
      September 14, 2015 Reply

      Hey John, thanks for replying!

      My goal is to be able to control the logs by changing a global variable at runtime, something like `window.debugMode = true', that would turn ON all $log calls.

      I know I can do this by checking the global value in the decorator, but I would like to accomplish this in a more "angularish way". Any ideas?

        John G. Gainfort, Jr.
        September 16, 2015 Reply

        So some ways could be to set an event listener on the window within you application, something like $window.$on('someEvent', onTheEvent), or put a $watch on a property on the $window.

Leave a reply