Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 879
user3141592 Avatar asked Jun 12 '14 13:06

user3141592


People also ask

Which one is better for console logging?

log() method is preferred over simply using an alert() method.

Is console log in production bad?

Generally yes, its not a great idea to expose log messages in your production code. Ideally, you should remove such log messages with a build script before deployment; but many (most) people do not use a build process (including me).

Can you use console log in Angular?

Programmers frequently use console. log to record errors or other informational messages in their Angular applications. Although this is fine while debugging your application, it's not a best practice for production applications.

Why do we log things to the console?

console. log specifically is a method for developers to write code to inconspicuously inform the developers what the code is doing. It can be used to alert you that there's an issue, but shouldn't take the place of an interactive debugger when it comes time to debug the code.


2 Answers

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

like image 115
Steve Klösters Avatar answered Oct 08 '22 19:10

Steve Klösters


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.

like image 30
Mistalis Avatar answered Oct 08 '22 19:10

Mistalis