Skip to main content

How to handle console.log programmatic in global scope

Methods

Since console isn’t yet formally covered by a specification, implementations vary. In Node it’s closely tied to standard input output, referred to as “stdio” by the documentation. This gives rise to error and log methods that will be printed to the appropriate output stream.
Most implementations give us convenient ways of separating output for debugging messages, errors, and warnings:

console.log('This is merely an informational debug message');
console.warn('This is a warning');
console.error('This is an error');

Inspection and Concatenation

In most browsers and Node, objects will be automatically printed in a readable format when using console.log. That means printing variables is possible without any extra effort:
console.log({ alex: "some dude" });

How to handle Console.log Programmatic globally?

// Declare flag values used as parameters to Fixconsole() method.
var ALERT_ON = false;  // Note: if 'true' -> all console logs become alert()  var DEBUG_MODE_ON = true;  // This enables console.log()
/**   Call once at beginning to ensure your app can safely call console.log() 
 *    and console.dir(), even on browsers that don't support it.  
 *    You may not get useful logging on those browsers, 
 *    but at least you won't generate errors.  
 *    @param alertFallback If 'true', all logs become alerts, if necessary.   
 *    (not usually suitable for production) 
 **/ 

function fixConsole(alertFallback,debugModeON) {
//alert('fixconsole -> alertFallback ='+alertFallback+'; debugModeON ='+debugModeON);
if (typeof console === "undefined") {
 console = {}; // define it if it doesn't exist already     
}     
if (typeof console.log === "undefined") {
 if (alertFallback) {
  console.log = function(msg) {
  alert(msg);
  }; 
 } else {
  console.log = function() {}; 
 }
 }else{
    //debug mode on = true
if (!debugModeON) {    console = console || {};    console.log = function(){};}
} 
if (typeof console.dir === "undefined") {
  if (alertFallback) {
 // THIS COULD BE IMPROVED - maybe list all the object properties?               console.dir = function(obj) {
 alert("DIR: "+obj); 
  };         
  } else {
     console.dir = function() {};
 }
}else{
 // debug mode on = true
if (!debugModeON) {    console = console || {};    console.dir = function(){}; }
 } 
}


Conclusion

The console object provides a surprisingly useful amount of functionality. If you’re writing lightweight Node programs, or want to debug something in a relatively modern browser (or browser with suitable developer tools), then try to take advantage of it rather than relying on unnecessary libraries.
In general, when logging with console:
  • Use the correct logging method so redirection works as expected
  • Quickly append variables to messages using console.log('Message:', value)
  • Use console to automatically inspect variables
Places you can view the console! Just to have them all in one answer.
Firefox
(you can also now use Firefox's built in developer tools Ctrl+Shift+J (Tools > Web Developer > Error Console), but Firebug is much better; use Firebug)
Safari and Chrome
Basically the same.
Internet Explorer
Don't forget you can use compatibility modes to debug IE7 and IE8 in IE9 or IE10
If you must access the console in IE6 for IE7 use the Firebug Lite bookmarklet
http://getfirebug.com/firebuglite/ look for stable bookmarklet
Opera
iOS
Works for all iPhones, iPod touch and iPads.
Now with iOS 6 you can view the console through Safari in OS X if you plug in your device. Or you can do so with the emulator, simply open a Safari browser window and go to the "Develop" tab. There you will find options to get the Safari inspector to communicate with your device.
Windows Phone, Android
Both of these have no console built in and no bookmarklet ability. So we use http://jsconsole.com/ type :listen and it will give you a script tag to place in your HTML. From then on you can view your console inside the jsconsole website.
iOS and Android
You can also use http://html.adobe.com/edge/inspect/ to access web inspector tools and the console on any device using their convenient browser plugin.

Older browser problems
Lastly older browsers (thanks again Microsoft) will crash if you use console.log in your code and not have the developer tools open at the same time. Luckily its an easy fix. Simple use the below code snippet at the top of your code and good old IE should leave you alone:
 if(!window.console){ window.console = {log: function(){} }; } 

Comments

Popular posts from this blog

ExtJS - Grid panel features

What can we do with ExtJS GridPanel? I have to develop a lot of applications in my web app and I see that grid component of ExtJS may fit in. However, I am not aware of what all things I can do with the - off the shelf available framework pieces - available plug-ins in the marketplace and - custom development through my own developers This is a typical question that we hear from the business users who wants to design an application by keeping the framework’s capability in perspective. In this article I have tried to put the list of stuff you can do with grid and hopefully that shall enable you to take advantage of the beauty of ExtJS. Pre-requisites This article assumes that you are familiar with basics of ExtJS What are the available options? In this section I will be taking you through some of the commonly seen usage of ExtJS grid panel. While covering all the capabilities of grid may not be possible, I am sure it will be helpful for the business users who want to

Ext4 Apply Store Filtering

In extjs4.1: There are many way for store filtering . Some of code i give here Filtering by single field: store . filter ( 'eyeColor' , 'Brown' );   Alternatively, if filters are configured with an  id , then existing filters store may be  replaced by new filters having the same  id . Filtering by single field: store . filter ( "email" , /\.com$/ );   Using multiple filters: store . filter ([ { property : "email" , value : /\.com$/ }, { filterFn : function ( item ) { return item . get ( "age" ) > 10 ; }} ]);   Using  Ext.util.Filter  instances instead of config objects (note that we need to specify the root config option in this case): store . filter ([ Ext . create ( ' Ext.util.Filter ' , {   property : "email" , value : /\.com$/ , root : 'data' }),   Ext . create ( ' Ext.util.Filter ' , {   filterFn : function ( item ) {   return item . get ( &

EXT JS 4: EMPTY VALUE IN A COMBOBOX

EXT JS 4: EMPTY VALUE IN A COMBOBOX Often, in an Ext JS combobox, it is difficult to go back to an empty value once you have selected an item, particularly if “forceSelection” is set to true.  Here is my roundup of alternative solutions found from around the web… 1. Override beforeBlur The solution from   http://www.sencha.com/forum/showthread.php?182119-How-To-Re-Empty-ComboBox-when-forceSelection-is-Set-To-TRUE  overrides beforeBlur on the combbox to clear out lastSelection.  Here is a copy of the override from the thread: 1 2 3 4 5 6 7 8 9 10 11 12 13 Ext.create( 'Ext.form.field.ComboBox' , {      ...      allowBlank: true ,      forceSelection: true ,      beforeBlur: function (){          var value = this .getRawValue();          if (value == '' ){              this .lastSelection = [];          }          this .doQueryTask.cancel();         this .assertValue();      } }); Or to apply the o