Will use of the debugging feature console.log reduce JavaScript execution performance? Will it affect the speed of script execution in production environments?
Is there an approach to disable console logs in production environments from a single configuration location?
Actually, console.log is a lot slower than an empty function. Running this jsPerf test on my Chrome 38 gives stunning results:
when the browser console is closed, calling console.log is about 10 000 times slower than calling an empty function,
and when the console is open, calling it is as much as 100 000 times slower.
Not that you'll notice the performance lag if you have a reasonable number of console.… calls firing once (a hundred will take 2 ms on my install of Chrome – or 20 ms when the console is open). But if you log stuff to the console repeatedly – for instance, hooking it up through requestAnimationFrame – it can make things janky.
Update:
In this test I've also checked out the idea of a custom “hidden log” for production – having a variable which holds log messages, available on demand. It turns out to be
about 1 000 times faster than the native console.log,
and obviously 10 000 times faster if the user has his console open.
If you are going to have this on a public site or something, anyone with little knowledge on using the developer tools can read your debug messages. Depending on what you are logging, this may not be a desirable behavior.
One of the best approaches is to wrap the console.log in one of your methods, and where you can check for conditions and execute it. In a production build, you can avoid having these functions. This Stack Overflow question talks in details about how to do the same using the Closure compiler.
So, to answer your questions:
Yes, it will reduce the speed, though only negligibly.
But, don't use it as it's too easy for a person to read your logs.
The answers to this question may give you hints on how to remove them from production.
const DEBUG = true / false
DEBUG && console.log('string')
Will use of the debugging feature console.log reduce JavaScript
execution performance? Will it affect the speed of script execution in
production environments?
Of course, console.log() will reduce your program's performance since it takes computational time.
Is there an approach to disable console logs in production
environments from a single configuration location?
Put this code at the beginning of your script to override the standard console.log function to an empty function.
console.log = function () { };
If you create a shortcut to the console in a common core script, eg:
var con = console;
and then use con.log("message") or con.error("error message") throughout your code, on production you can simply rewire con in the core location to:
var con = {
log: function() {},
error: function() {},
debug: function() {}
}
Any function call will slightly reduce performance. But a few console.log's should not have any noticeable effect.
However it will throw undefined errors in older browsers that don't support console
The performance hit will be minimal, however in older browsers it will cause JavaScript errors if the users browsers console is not open log is not a function of undefined. This means all JavaScript code after the console.log call will not execute.
You can create a wrapper to check if window.console is a valid object, and then call console.log in the wrapper. Something simple like this would work:
window.log = (function(console) {
var canLog = !!console;
return function(txt) {
if(canLog) console.log('log: ' + txt);
};
})(window.console);
log('my message'); //log: my message
Here is a fiddle: http://jsfiddle.net/enDDV/
I made this jsPerf test: http://jsperf.com/console-log1337
It doesn't seem to take any longer than other function calls.
What about browsers that doesn't have a console API? If you need to use console.log for debugging, you might include a script in your production deployment to override the console API, like Paul suggests in his answer.
I do it this way to maintain original signature of console methods. In a common location, loaded before any other JS:
var DEBUG = false; // or true
Then throughout code
if (DEBUG) console.log("message", obj, "etc");
if (DEBUG) console.warn("something is not right", obj, "etc");
I prefer it doing this way:
export const println = (*args,) => {
if(process.env.NODE_ENV === "development") console.log(args)
}
and then use println everywhere in your code.
Related
I am getting a totally bizarre issue in Chrome v. 33 that looks as if the string comparison operator is broken. It only occurs with the developer tools closed. I have the following function:
function TabSelected(data) {
var tab, was_design;
this.data = data;
tab = this.data.tab;
was_design = tab === 'design';
if (this.data.tab === 'design') {
this.tab = 1;
} else {
this.tab = 2;
console.log('was_design');
console.log(was_design);
console.log('is_design');
console.log(tab === 'design');
}
}
Which I call like so:
new TabSelected({
tab: 'design'
});
I have a setInterval running that runs this code every 50 ms. Most of the time, the if statement picks the first code path, so nothing gets logged to the console. However, after about ~8 seconds, it goes down the else code path. When I open the developer tools afterwards (since the bug doesn't happen when they're closed), I see the following log output:
was_design (index):96624
false (index):96625
is_design (index):96626
true (index):96627
I am... confused by this. I've also tried logging the contents of tab, which is in fact 'design', and logging this, which is a new TabSelected instance.
Am I losing my mind? Is Chrome losing it's mind?
UPDATE: I was able to reproduce it in a simplified setting: http://jsfiddle.net/WBpLG/24/. I'm pretty sure this is a bug with Chrome and I've filed an issue, see answer below.
Make this change and the problem should go away:
if (this.data.tab === 'design') {
to
if (String(this.data.tab) === 'design') {
However, I can confirm that typeof this.data.tab === 'string' both before the if clause and during the else, so I think this is only a partial answer at best.
Alternatively, I can also clear the problem by adjusting NewElementButtonSectionOpened.prototype.previous_requirement on line 59440:
// Create a single instance of the requirement and store it in the closure.
var cachedReq = new TabSelected({ tab: 'design' });
// Now just return that one instance over and over again.
NewElementButtonSectionOpened.prototype.previous_requirement = function() {
// deleted line: return new TabSelected({ tab: 'design' });
return cachedReq;
};
While both of these solutions fix the problem on my machine, it is not clear to me why this works.
I am afraid to mention it, but at one point, I was also able to prevent the error from happening by adding a throw new Error("..."); line in your else block. In other words, changing something in the else block altered the behavior of the if check. My only clue here is that the length of the error message mattered. For a while there, I could clear the error or cause the error consistently by altering the length of an error message that would never be thrown. This is so bizarre that I must surely have been mistaken, and indeed, I can no longer replicate it.
However, this is an extremely large JavaScript file. Maybe there is something to that. Maybe it is just a ghost story. This problem is certainly quite creepy enough without it, but just in case somebody else sees something similar... You aren't alone.
I was able to create a simple reproduction case, so I've filed a bug with Chromium.
The necessary conditions seem to be: a setInterval or repeating setTimeout, an expensive computation in the body of the interval, a call to a new Object passing data that contains a string, and a string comparison.
I noticed that qUnit doesn't give any notice when an exception happens in a later part of the test. For example, running this in a test():
stop();
function myfun(ed) {
console.log('resumed');
start(); //Resume qunit
ok(1,'entered qunit again');
ok(ed.getContent()== 'expected content') // < causes exception, no getContent() yet.
}
R.tinymce.onAddEditor.add(myfun)
in an inner iframe on the page will cause an exception (TypeError: ed.getContent is not a function),
but nothing in Qunit status area tells this. I see 0 failures.
(R being the inner iframe, using technique here: http://www.mattevanoff.com/2011/01/unit-testing-jquery-w-qunit/) Would I be correct in assuming this isn't the best way to go for testing sequences of UI interaction that cause certain results? Is it always better to use something like selenium, even for some mostly-javascript oriented frontend web-app tests?
As a side note, the Firefox console shows the console.log below the exception here, even though it happened first... why?
If you look into qUnit source code, there are two mechanisms handling exceptions. One is controlled by config.notrycatch setting and will wrap test setup, execution and teardown in try..catch blocks. This approach won't help much with exceptions thrown by asynchronous tests however, qUnit isn't the caller there. This is why there is an additional window.onerror handler controlled by Test.ignoreGlobalErrors setting. Both settings are false by default so that both kinds of exceptions are caught. In fact, the following code (essentially same as yours but without TinyMCE-specific parts) produces the expected results for me:
test("foo", function()
{
stop();
function myfun(ed)
{
start();
ok(1, 'entered qunit again');
throw "bar";
}
setTimeout(myfun, 1000);
});
I first see a passed tests with the message "entered qunit again" and then a failed one with the message: "uncaught exception: bar." As to why this doesn't work for you, I can see the following options:
Your qUnit copy is more than two years old, before qUnit issue 134 was fixed and a global exception handler added.
Your code is changing Test.ignoreGlobalErrors setting (unlikely).
There is an existing window.onerror handler that returns true and thus tells qUnit that the error has been handled. I checked whether TinyMCE adds one by default but it doesn't look like it does.
TinyMCE catches errors in event handlers when calling them. This is the logical thing to do when dealing with multiple callbacks, the usual approach is something like this:
for (var i = 0; i < callbacks.length; i++)
{
try
{
callbacks[i]();
}
catch (e)
{
console.error(e);
}
}
By redirecting all exceptions to console.error this makes sure that exceptions are still reported while all callbacks will be called even if one of them throws an exception. However, since the exception is handled jQuery can no longer catch it. Again, I checked whether TinyMCE implements this pattern - it doesn't look like it.
Update: Turns out there is a fifth option that I didn't think of: the exception is fired inside a frame and qUnit didn't set up its global error handler there (already because tracking frame creation is non-trivial, a new frame can be created any time). This should be easily fixed by adding the following code to the frame:
window.onerror = function()
{
if (parent.onerror)
{
// Forward the call to the parent frame
return parent.onerror.apply(parent, arguments);
}
else
return false;
}
Concerning your side-note: the console object doesn't guarantee you any specific order in which messages appear. In fact, the code console.log("foo");throw "bar"; also shows the exception first, followed by the log message. This indicates that log messages are queued and handled delayed, probably for performance reasons. But you would need to look into the implementation of the console object in Firefox to be certain - this is an implementation detail.
I am interested in monitoring javascript errors and logging the errors with the callstack.
I am not interested to wrap everything in try-catch blocks.
According to this article http://blog.errorception.com/2011/12/call-stacks-in-ie.html
it's possible inside window.onerror "recursively call .caller for each function in the stack to know the previous function in the stack"
I tried to get the callstack:
window.onerror = function(errorMsg, url, lineNumber)
{
var stk = [], clr = arguments.callee.caller;
while(clr)
{
stk.push("" + clr);
clr = clr.caller;
}
// Logging stk
send_callstack_to_log(stk);
}
but only one step is possible even if the callstack was much longer:
(function()
{
function inside() {it.will.be.exception;};
function middle() {inside()};
function outside() {middle()}
outside();
})();
One step isn't interesting because onerror arguments give me even more information about it.
Yes, I tried it with IE according the article I mentioned above.
Remark: I also tried to open an account on "ERRORCAEPTION" to gather error log. I tested it with IE and "ERRORCAEPTION" recognize that the errors are coming from IE, but I can't find any callstack information in the log I've got there.
Unfortunately this log will not always be available, it lacks line numbers, you can not really rely on it.
Try https://qbaka.com
Qbaka automatically overload bunch of JavaScript functions like addEventListener, setTimeout, XMLHtppRequest, etc so that errors happening in callbacks are automatically wrapped with try-catch and you will get stacktraces without any code modification.
You can try atatus which provides javascript contextual error tracking: https://www.atatus.com/
Take a look here:
https://github.com/eriwen/javascript-stacktrace
That's the one I use on Muscula, a service like trackjs.
I have wrote a program to monitor js error. maybe it will help.
I used three kind of methods to catch exceptions, such as window.onerror, rewrite console.error and window.onunhandledrejection. So I can get Uncaught error, unhandled promise rejection and Custom error
Take a look here: https://github.com/a597873885/webfunny_monitor
or here: https:www.webfunny.cn
It will be help
While debugging some client side javascript today in Firefox, I ran into something that I found quite odd and little unnerving. Also, I was unable to duplicate this behavior while debugging the same script with IE / VS2010.
I created a simple example html document to illustrate the anomally I am seeing.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js" type="text/javascript" ></script>
</head>
<body id="main_body">
<script type="text/javascript">
$(function () {
$(".test-trigger").on("click", function () {
loadStuff();
console && console.log && console.log("this will probably happen first.");
});
});
function loadStuff() {
$.get("http://google.com/")
.fail(function () {
console && console.log && console.log("this will probably happen second.");
});
}
</script>
<button class="test-trigger">test</button>
</body>
</html>
If you load this document into Firefox (I am using version 13.0 with Firebug version 1.10.1 on Windows 7), click test, and view the console tab in Firebug you should notice that the get request fails (cross domain violation that has nothing to do with the point I'm trying to make here), and then you will most likely see:
this will probably happen first.
this will probably happen second.
Now, place breakpoints on lines 13 and 20:
13: console && console.log && console.log("this will probably happen first.");
20: console && console.log && console.log("this will probably happen second.");
If you click test again you will break on line 13 as expected. Now, resume execution. If your experience is like mine, you will not break on line 20. Also if you switch to the console tab you will see the following sequence of log output:
this will probably happen second.
this will probably happen first.
To me, this suggests that the fail handler of the ajax request is being executed in a thread other than that which the click handler is being executed in. I have always been led to believe that all the javascript for a single page will be executed by a single thread in any browser. Am I missing something really obvious here? Thanks for any insight on this observation.
Oh, if I debug the same page running in IE using Visual Studio, both breakpoints are hit as I would expect.
I think it's safe to assume that the anomaly you're observing is caused by how Firebug implements breakpoints/works under the hood. I can't confirm that though. This also happens with FF 14 on OS X.
Unless jQuery immediately executes your fail() function and surpasses the whole XMLHttpRequest object, then there is a guarantee that the ordering of the statements will be this will probably happen first. then this will probably happen second..
Given the single threaded nature of JavaScript, functions will be essentially atomic; they will not get interrupted by a callback.
It seems as though you're trying to simulate what would happen if the click function takes a while to finish executing after calling loadStuff(). The click function shouldn't get interrupted by the fail method executing (mind == blown that you found a way to make that happen).
To take breakpoints out of the equation, here's a modified version. The rest of the markup is unchanged.
$(function () {
$(".test-trigger").on("click", function () {
loadStuff();
for (var i = 0; i < 1000000000; i++)
{
//block for some interesting calculation or something
}
console && console.log && console.log("this will probably happen first.");
});
});
function loadStuff() {
$.get("http://google.com/")
.fail(function () {
console && console.log && console.log("this will probably happen second.");
});
}
The click function clearly takes a long time to execute, after calling loadStuff(), but the console will still reflect the correct order of the log statements here. Also worth noting, if you insert the same breakpoints, the ordering will be invalid, like the original example.
I'd file an issue for this with Firebug.
$.get("http://google.com/") is asynchronous, it is a race on what gets done first. The first time it is slower since it needs to make the call and the call happens later in the code execution. The call is already cached with the second request, so it happens to execute quicker.
If you need something to be done before the request goes out use beforeSend().
To my experience, Firebug doesn't work well when putting breakpoints in asynchronous code.
I.e. if you have one straight line of execution and put breakpoints in it, you'll be fine. However if you introduce asynchronicity e.g. by using setTimeout, you won't hit the breakpoint in that "parallel" line (which of course is not parallel really, the JS engine switches between the tasks). I've been experiencing it a lot in last couple of months.
In Chrome, it seems to work fine (they defer timeouts intelligently somehow). Perhaps because Chrome dev tools are built-in to the browser, it's easier to manipulate the timeouts. Firebug is "just" an add-on and perhaps it may be tricky to do it correctly.
A simple script to reproduce the issue:
Put breakpoints in lines when I assign value to x, y, z.
First, you'll hit a breakpoint on the line x = 1. Use F10 to step over. You won't hit a breakpoint on the line with z = 3 ever will hit a breakpoint on the line with z = 3 only if you're quick enough with pressing F10 (Firefox 14, Firebug 1.10).
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
function foo(){
var x = 1;
setTimeout(bar, 2000);
var y = 2;
}
function bar(){
var z = 3;
}
foo();
</script>
</body>
</html>
I have a bunch of console.log() calls in my JavaScript.
Should I comment them out before I deploy to production?
I'd like to just leave them there, so I don't have to go to the trouble of re-adding the comments later on if I need to do any more debugging. Is this a bad idea?
It will cause Javascript errors, terminating the execution of the block of Javascript containing the error.
You could, however, define a dummy function that's a no-op when Firebug is not active:
if(typeof console === "undefined") {
console = { log: function() { } };
}
If you use any methods other than log, you would need to stub out those as well.
As others have already pointed it, leaving it in will cause errors in some browsers, but those errors can be worked around by putting in some stubs.
However, I would not only comment them out, but outright remove those lines. It just seems sloppy to do otherwise. Perhaps I'm being pedantic, but I don't think that "production" code should include "debug" code at all, even in commented form. If you leave comments in at all, those comments should describe what the code is doing, or the reasoning behind it--not blocks of disabled code. (Although, most comments should be removed automatically by your minification process. You are minimizing, right?)
Also, in several years of working with JavaScript, I can't recall ever coming back to a function and saying "Gee, I wish I'd left those console.logs in place here!" In general, when I am "done" with working on a function, and later have to come back to it, I'm coming back to fix some other problem. Whatever that new problem is, if the console.logs from a previous round of work could have been helpful, then I'd have spotted the problem the first time. In other words, if I come back to something, I'm not likely to need exactly the same debug information as I needed on previous occasions.
Just my two cents... Good luck!
Update after 13 years
I've changed my mind, and now agree with the comments that have accumulated on this answer over the years.
Some log messages provide long-term value to an application, even a client-side JavaScript application, and should be left in.
Other log messages are low-value noise and should be removed, or else they will drown out the high-value messages.
If you have a deployment script, you can use it to strip out the calls to console.log (and minify the file).
While you're at it, you can throw your JS through JSLint and log the violations for inspection (or prevent the deployment).
This is a great example of why you want to automate your deployment. If your process allows you to publish a js file with console.logs in it, at some point you will do it.
To my knowledge there is no shorter method of stubbing out console.log than the following 45 characters:
window.console||(console={log:function(){}});
That's the first of 3 different versions depending on which console methods you want to stub out all of them are tiny and all have been tested in IE6+ and modern browsers.
The other two versions cover varying other console methods. One covers the four basics and the other covers all known console methods for firebug and webkit. Again, in the tiniest file sizes possible.
That project is on github: https://github.com/andyet/ConsoleDummy.js
If you can think of any way to minimize the code further, contributions are welcomed.
-- EDIT -- May 16, 2012
I've since improved on this code. It's still tiny but adds the ability to turn the console output on and off: https://github.com/HenrikJoreteg/andlog
It was featured on The Changelog Show
You should at least create a dummy console.log if the object doesn't exist so your code won't throw errors on users' machines without firebug installed.
Another possibility would be to trigger logging only in 'debug mode', ie if a certain flag is set:
if(_debug) console.log('foo');
_debug && console.log('foo');
Hope it helps someone--I wrote a wrapper for it a while back, its slightly more flexible than the accepted solution.
Obviously, if you use other methods such as console.info etc, you can replicate the effect. when done with your staging environment, simply change the default C.debug to false for production and you won't have to change any other code / take lines out etc. Very easy to come back to and debug later on.
var C = {
// console wrapper
debug: true, // global debug on|off
quietDismiss: false, // may want to just drop, or alert instead
log: function() {
if (!C.debug) return false;
if (typeof console == 'object' && typeof console.log != "undefined") {
console.log.apply(this, arguments);
}
else {
if (!C.quietDismiss) {
var result = "";
for (var i = 0, l = arguments.length; i < l; i++)
result += arguments[i] + " ("+typeof arguments[i]+") ";
alert(result);
}
}
}
}; // end console wrapper.
// example data and object
var foo = "foo", bar = document.getElementById("divImage");
C.log(foo, bar);
// to surpress alerts on IE w/o a console:
C.quietDismiss = true;
C.log("this won't show if no console");
// to disable console completely everywhere:
C.debug = false;
C.log("this won't show ever");
this seems to work for me...
if (!window.console) {
window.console = {
log: function () {},
group: function () {},
error: function () {},
warn: function () {},
groupEnd: function () {}
};
}
Figured I would share a different perspective. Leaving this type of output visible to the outside world in a PCI application makes you non-compliant.
I agree that the console stub is a good approach. I've tried various console plugins, code snippets, including some fairly complex ones. They all had some problem in at least one browser, so I ended up going with something simple like below, which is an amalgamation of other snippets I've seen and some suggestions from the YUI team. It appears to function in IE8+, Firefox, Chrome and Safari (for Windows).
// To disable logging when posting a production release, just change this to false.
var debugMode = false;
// Support logging to console in all browsers even if the console is disabled.
var log = function (msg) {
debugMode && window.console && console.log ? console.log(msg) : null;
};
Note: It supports disabling logging to the console via a flag. Perhaps you could automate this via build scripts too. Alternatively, you could expose UI or some other mechanism to flip this flag at run time. You can get much more sophisticated of course, with logging levels, ajax submission of logs based on log threshold (e.g. all Error level statements are transmitted to the server for storage there etc.).
Many of these threads/questions around logging seem to think of log statements as debug code and not code instrumentation. Hence the desire to remove the log statements. Instrumentation is extremely useful when an application is in the wild and it's no longer as easy to attach a debugger or information is fed to you from a user or via support. You should never log anything sensitive, regardless of where it's been logged to so privacy/security should not be compromised. Once you think of the logging as instrumentation it now becomes production code and should be written to the same standard.
With applications using ever more complex javascript I think instrumentation is critical.
As other have mentions it will thrown an error in most browsers. In Firefox 4 it won't throw an error, the message is logged in the web developer console (new in Firefox 4).
One workaround to such mistakes that I really liked was de&&bug:
var de = true;
var bug = function() { console.log.apply(this, arguments); }
// within code
de&&bug(someObject);
A nice one-liner:
(!console) ? console.log=function(){} : console.log('Logging is supported.');
Yes, it's bad idea to let them running always in production.
What you can do is you can use console.debug which will console ONLY when the debugger is opened.
https://developer.mozilla.org/en-US/docs/Web/API/console/debug