67

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?

jediz
  • 4,459
  • 5
  • 36
  • 41
user3141592
  • 1,069
  • 2
  • 10
  • 20

2 Answers2

81

$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.

jediz
  • 4,459
  • 5
  • 36
  • 41
Steve Klösters
  • 9,427
  • 2
  • 42
  • 53
  • 2
    Thanks. Especially for directing me to the source code. I'm learning that's frequently the place to go. – user3141592 Jun 12 '14 at 14:40
  • I figured there must be more than just avoiding missing console. There's not much, but the decorator tip and bonus feature you mention are good to know. – user3141592 Jun 12 '14 at 14:48
  • 9
    +1 I think it's important to note that 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. `console.log` is a supported in IE 8 as long as the dev tools are open. See [this](http://stackoverflow.com/questions/690251/what-happened-to-console-log-in-ie8) question as a reference... – War10ck Jun 12 '14 at 15:36
  • 61
    Using $log has a downside as well: if you use console.log you can see the file and the line number of the actual logging. With $log it will always show angular.js as the source of the log in your console. – wvdz Oct 26 '14 at 09:42
  • 3
    It's 3 characters shorter ;) – Patrick Borkowicz Aug 13 '15 at 18:15
  • 19
    Another bonus, it allows you to turn off debug logging in production, with $logProvider.debugEnabled(false); – JimJty Mar 23 '16 at 22:36
10

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.

Mistalis
  • 17,793
  • 13
  • 73
  • 97