How to safely wrap `console.log`?

Suppose I want to include some calls in console.log for some legitimate production reason, say for something like a unit test harness. Obviously, I would not want this to raise a premature exception if there is no console in the browser or if not.

What is the best way to create a simple log function to write stuff to the console or without crashing without errors if the console is missing?

The accepted answer to the question related above:

 var log = Function.prototype.bind.call(console.log, console); log.apply(console, ["this", "is", "a", "test"]); 

Could this log function be called normally in IE, and using apply here just to show it? And from a related question, I assume that this will not succeed if the IE console is closed when it starts, so log will not work even after opening the console, right? If this is not the case, can someone explain how this works?

This ycombinator article seems relevant. Are they talking about the same IE behavior as the question related above?

 Function.prototype.apply.apply(console.log, [console, arguments]); 

It works both on IE9, broken console.log, and on a regular .log console from other providers. The same hack as using Array.prototype.slice to convert arguments to a real array.

This works well on my Chrome console.

 function echo(){ Function.prototype.apply.apply(console.log, [console, arguments]); } 

Simplified:

 function echo(){ Function.apply.call(console.log, console, arguments); } 

Add a check and a refund:

 function echo(){ return window.console && console.log && Function.apply.call(console.log, console, arguments); } 

The above example seems adequate to me. However, I do not have IE on hand to test it. Is this a smart approach for secure console.log packaging?




Other questions

Following the link below in the navigation, we see the code:

 Function.prototype.call.call(console.log, console, Array.prototype.slice.call(arguments)); 

What is the purpose of converting arguments to an array in this case? I think in some browser this will not work if you do not? And, unlike opera behavior and hassle-free browsers, shouldn't something like this pretty much work for any other browser? And prototype serves the purpose in the examples above, or we're just pedantic ... Function.call.call or Object.call.call or, if it is important, isNaN.call.call seems to work just as well as Function.prototype.call.call .

+47
javascript internet-explorer logging console wrapper
Jan 09 '12 at 8:32
source share
11 answers

Could this log function be called normally in IE, and using apply here just to show it?

Yes and yes. This specific example was aimed directly at the “is this a real function” part of the related question.

And I suppose from a related question that this will not succeed if the IE console is closed when it starts, so the log will not work even after the console opens, right?

Right. As explained in my answer to this question, the console object is not displayed until the developer tools open for a specific tab. Most developers use a console layout, in which case the Function#bind approach becomes a bit obsolete, as you can also use the Function#apply.apply .

What is the purpose of converting the arguments to an array in this case?

No, he is superfluous. If this is not a regular implementation of the log, in this case the developer may have a reason for converting the arguments object to an array.

And the prototype serves the purpose in the above examples, or are we just pedantic ...

Good, yes and no. Some developers may unexpectedly change Function.call to a user-defined function or value. Of course, they can break Function.prototype.call too, but this is much less likely to happen by accident.

+7
Jan 09 '12 at 19:59
source share

The problem with wrappers is that they will obfuscate the file name and line number of the log message source.

Simple IE7 and lower configuration that saves line numbering for other browsers:

 /* console shim*/ (function () { var f = function () {}; if (!window.console) { window.console = { log:f, info:f, warn:f, debug:f, error:f }; } }()); 
+19
Jun 17 '13 at 17:51
source share

Sorry, there was a mistake in my post. I don’t know how I missed it.

PROPER way to create a global console object if it does not exist:

 if (typeof console === "undefined"){ console={}; console.log = function(){ return; } } 
+16
Jul 22 2018-12-22T00:
source share

I like to use:

 'console' in window && console.log("Boom!"); 

It works in all browsers and is easy to understand.

+6
Jun 21 '13 at 4:10
source share
+4
Jan 9 2018-12-12T00:
source share

Try using the code snippet below ... (this is my preferred approach because it makes you independent of window.console)

 var logger = (function (c) { "use strict"; var m = { log: function (a, t) { if (!c) { return; /* return or call your custom function here */ } var l = c.log, f = t === undefined ? l : (this.__dict__[t] || l); f.apply(c, a) }, __dict__: { "trace": c.trace, "debug": c.debug, "info": c.info, "warn": c.warn, "error": c.error } }; return { trace: function () { m.log(arguments, "trace"); }, debug: function () { m.log(arguments, "debug"); }, info: function () { m.log(arguments, "info"); }, warn: function () { m.log(arguments, "warn"); }, error: function () { m.log(arguments, "error"); }, log: function () { m.log(arguments, undefined); } }; }(window.console)) 

So you can try this in your code and see the result

 logger.info("Hello"); logger.trace("Hello"); logger.debug("Hello"); logger.warn("Hello"); logger.error("Hello"); logger.log("Hello"); 
+3
Feb 18 '14 at 14:26
source share

As a slight variation on Chris’s answer, simply define the “log” as a “console” property with an empty function:

 if (typeof console === "undefined") { console = { log: function () { return; } }; } 
+1
Aug 08 2018-12-12T00:
source share

Paul Irish has a nice light box / replacement for console.log() .

http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/

Benefits:

  • Prevent errors if the console is not around (i.e. IE)
  • It saves the history of logs, so you can look in the past if your console is added later (for example, firebug lite).
  • Lightweight and simple.
  • A very fast type is log() or window.log() .
0
May 2 '13 at 3:43
source share

Use consolation

My ridiculously overloaded console:

  • prevents errors if there is no console
  • prevents logging during production if you leave console.log statements in your code
  • supports console.error , console.group and all such other methods
  • still gives you back outputs for log statements

It's amazing.

But in fact, you should not leave console statements that lie in your code.

Here's a shiver! View: Consolation.js

0
Aug 28 '13 at 16:53
source share

CoffeeScript:

 empty_function = -> return if !window.console? window.console = {} for fn in ['log', 'info', 'warn', 'debug', 'error'] if (typeof window.console[fn] isnt 'function') window.console[fn] = empty_function 

JS:

 (function() { var empty_function, fn, i, len, ref; empty_function = function() {}; if (window.console == null) { window.console = {}; ref = ['log', 'info', 'warn', 'debug', 'error']; for (i = 0, len = ref.length; i < len; i++) { fn = ref[i]; if (typeof window.console[fn] !== 'function') { window.console[fn] = empty_function; } } } }).call(this); 
0
Jan 22 '17 at 12:15
source share

My solution is a little different. I create a standard shortcut for all calls to console.log: In my case, kag (whatever I want to report to the console).

I am testing IE if IE sent the results to a warning window. If Chrome is displayed in the console. This also means that IE will always work even when the console is closed:

the code:

 var iever = getInternetExplorerVersion(); if(iever>-1){ function kag(params){ alert(params); } } else { var kag = console.log.bind(console, "REPORT: "); } function getInternetExplorerVersion() { var rv = -1; if (navigator.appName == 'Microsoft Internet Explorer') { var ua = navigator.userAgent; var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})"); if (re.exec(ua) != null){ rv = parseFloat( RegExp.$1 ); } } return rv; } 
-one
Feb 06 '13 at 9:31
source share



All Articles