Why use angular's $log instead of console.log?

AngularjsLogging

Angularjs Problem Overview


I understand it is a best practice in angular to use $log instead of console.log. However, I can't find good documentation explaining the reasons. Why should a developer use $log?

Angularjs Solutions


Solution 1 - Angularjs

$log first checks if the browser supports console.log (IE 8, for example, doesn't). This prevents errors being displayed on IE 8. Note: this doesn't mean it will log anything on IE 8, it simply means it won't throw the error.

Next to that, it also allows you to decorate and mock $log for extending and testing purposes, if you are so inclined. You could for example decorate it to log to an array for IE 8 support.

A bonus feature: if you pass it a JavaScript Error instance, it will attempt to format it nicely. This can be found out by reading the source code.

EDIT: "It is not that IE 8 doesn't support console.log. It just doesn't create the console object until the dev tools are opened." See comments below for more details.

Solution 2 - Angularjs

Just to complete @Steve's answer (which is correct), $log also has the advantage of being turned off. Using this code you can disable the logging from $log:

app.config(function($logProvider) {
  $logProvider.debugEnabled(true);
});

This is very handy if you want to disable all logs at once, rather than delete them line by line manually.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3141592View Question on Stackoverflow
Solution 1 - AngularjsSteve KlöstersView Answer on Stackoverflow
Solution 2 - AngularjsMistalisView Answer on Stackoverflow