JavaScript: How do I print a message to the error console? - javascript

How can I print a message to the error console, preferably including a variable?
For example, something like:
print('x=%d', x);

Install Firebug and then you can use console.log(...) and console.debug(...), etc. (see the documentation for more).

console.error(message); // Outputs an error message to the Web Console
console.log(message); // Outputs a message to the Web Console
console.warn(message); // Outputs a warning message to the Web Console
console.info(message); // Outputs an informational message to the Web Console. In some browsers it shows a small "i" in front of the message.
You also can add CSS:
console.log('%c My message here', "background: blue; color: white; padding-left:10px;");
More info can be found here: https://developer.mozilla.org/en-US/docs/Web/API/console

Exceptions are logged into the JavaScript console. You can use that if you want to keep Firebug disabled.
function log(msg) {
setTimeout(function() {
throw new Error(msg);
}, 0);
}
Usage:
log('Hello World');
log('another message');

One good way to do this that works cross-browser is outlined in Debugging JavaScript: Throw Away Your Alerts!.

Here is a solution to the literal question of how to print a message to the browser's error console, not the debugger console. (There might be good reasons to bypass the debugger.)
As I noted in comments about the suggestion to throw an error to get a message in the error console, one problem is that this will interrupt the thread of execution. If you don't want to interrupt the thread, you can throw the error in a separate thread, one created using setTimeout. Hence my solution (which turns out to be an elaboration of the one by Ivo Danihelka):
var startTime = (new Date()).getTime();
function logError(msg)
{
var milliseconds = (new Date()).getTime() - startTime;
window.setTimeout(function () {
throw( new Error(milliseconds + ': ' + msg, "") );
});
}
logError('testing');
I include the time in milliseconds since the start time because the timeout could skew the order in which you might expect to see the messages.
The second argument to the Error method is for the filename, which is an empty string here to prevent output of the useless filename and line number. It is possible to get the caller function but not in a simple browser independent way.
It would be nice if we could display the message with a warning or message icon instead of the error icon, but I can't find a way to do that.
Another problem with using throw is that it could be caught and thrown away by an enclosing try-catch, and putting the throw in a separate thread avoids that obstacle as well. However, there is yet another way the error could be caught, which is if the window.onerror handler is replaced with one that does something different. Can't help you there.

If you use Safari, you can write
console.log("your message here");
and it appears right on the console of the browser.

To actually answer the question:
console.error('An error occurred!');
console.error('An error occurred! ', 'My variable = ', myVar);
console.error('An error occurred! ' + 'My variable = ' + myVar);
Instead of error, you can also use info, log or warn.

If you are using Firebug and need to support IE, Safari or Opera as well, Firebug Lite adds console.log() support to these browsers.

The WebKit Web Inspector also supports Firebug's console API (just a minor addition to Dan's answer).

A note about 'throw()' mentioned above. It seems that it stops execution of the page completely (I checked in IE8) , so it's not very useful for logging "on going processes" (like to track a certain variable...)
My suggestion is perhaps to add a textarea element somewhere in your document and to change (or append to) its value (which would change its text) for logging information whenever needed...

As always, Internet Explorer is the big elephant in rollerskates that stops you just simply using console.log().
jQuery's log can be adapted quite easily, but is a pain having to add it everywhere. One solution if you're using jQuery is to put it into your jQuery file at the end, minified first:
function log()
{
if (arguments.length > 0)
{
// Join for graceful degregation
var args = (arguments.length > 1) ? Array.prototype.join.call(arguments, " ") : arguments[0];
// This is the standard; Firebug and newer WebKit browsers support this.
try {
console.log(args);
return true;
} catch(e) {
// Newer Opera browsers support posting erros to their consoles.
try {
opera.postError(args);
return true;
}
catch(e)
{
}
}
// Catch all; a good old alert box.
alert(args);
return false;
}
}

Visit https://developer.chrome.com/devtools/docs/console-api for a complete console api reference
console.error(object[Obj,....])\
In this case, object would be your error string

function foo() {
function bar() {
console.trace("Tracing is Done here");
}
bar();
}
foo();
console.log(console); //to print console object
console.clear('console.clear'); //to clear console
console.log('console.log'); //to print log message
console.info('console.info'); //to print log message
console.debug('console.debug'); //to debug message
console.warn('console.warn'); //to print Warning
console.error('console.error'); //to print Error
console.table(["car", "fruits", "color"]);//to print data in table structure
console.assert('console.assert'); //to print Error
console.dir({"name":"test"});//to print object
console.dirxml({"name":"test"});//to print object as xml formate
To Print Error:- console.error('x=%d', x);
console.log("This is the outer level");
console.group();
console.log("Level 2");
console.group();
console.log("Level 3");
console.warn("More of level 3");
console.groupEnd();
console.log("Back to level 2");
console.groupEnd();
console.log("Back to the outer level");

console.log("your message here");
working for me.. i'm searching for this.. i used Firefox.
here is my Script.
$('document').ready(function() {
console.log('all images are loaded');
});
works in Firefox and Chrome.

The simplest way to do this is:
console.warn("Text to print on console");

To answer your question you can use ES6 features,
var var=10;
console.log(`var=${var}`);

This does not print to the Console, but will open you an alert Popup with your message which might be useful for some debugging:
just do:
alert("message");

With es6 syntax you can use:
console.log(`x = ${x}`);

Related

Execute JavaScript code to get the log from console using selenium webdriver or WatiN

(Sorry for being a bit descriptive)
I wanted to wait for a page to load completely but after searching on Google it seems that browsers react differently, when we try to use readyState or onLoad.
Also, for application I am working on, it seems that a particular log message ("TNP is ready") appears in console (chrome console or IE developer tool console), when the required page is loaded.
My plan is to execute a small JavaScript code on the browser, using Selenium WebDriver C# and WatiN C# (IE), to get this message from the console log.
Can this be done? Can I get the Last Log generated by console.log ?
Because when I execute the script it might happen that the message is already gone or yet to come. I need to fire it repeatedly.
Any suggestions?
This question, while not exactly a duplicate of In WatiN how to wait until postback is complete, is probably caused by the same thing.
The browser.WaitUntilComplete() method will wait for the page to finish loading, but if you have AJAX going on in the background as the page is loading then WaitUntilComplete won't do the trick.
From my research, there is no way to get log messages from the browser console unless you include some JavaScript to mirror the console and overwrite window.console and provide a mechanism for inspecting console messages.
(function(win) {
var console = win.console;
if (!console)
throw new Error("This browser does not support a debug console");
var mirror = {},
data = {};
var toString = Object.prototype.toString,
mirrorMethod = function(key) {
data[key] = [];
return function() {
data[key].push(arguments);
console[key].apply(console, arguments);
};
};
for (var key in console) {
if (toString.call(console[key]) == "[object Function]") {
mirror[key] = mirrorMethod(key);
}
}
win.console = mirror;
win.consoleMirror = {
getData: function(key) {
return data[key] || [];
}
};
}(this));
JSFiddle: http://jsfiddle.net/fyhLw0to/
And to use:
console.log("foo");
alert(consoleMirror.getData("log")[0][0]);
An alternative is to grab an element using WatiN that you need to interact with, and call WaitUntilExists:
var button = browser.Button("buttonIdThatDoesNotExistYet");
button.WaitUntilExists();
button.Click();
This way you don't have to hack the debug console, or hack XMLHttpRequest to infer when AJAX is done. Your tests will attempt to wait for elements to appear on the page before acting upon them. Test failures will be slower, but your tests should be more robust.

Javascript debug no console error

My script dont run till the end. And stops due to errors. But there is no console error output.
alert("yo");
var go = "";
go.push(null);
alert("yo2");
first alert works
Tested with Chrome and Firefox
No try catch blocks
Are there reasons for not showing up a console error, without knowing the whole code?
You should see the error: TypeError: Object has no method 'push'
Im getting it in chrome console.
The error message is saying that the push method cannot be run on the variable go.
This is because it is of the type String and thus does have the push method available.
The push method is used to add items into an Array like this:
go = []; // or you could use `go = Array()`;
go.push("A string");
go.push(null);
To output messages to the browser console, use console.log like this:
console.log("Some debug message");
console.log(go); // outputs the above array
I solved the problem by using try-catch:
try
{
var my_app = new My_App();
}
catch(e)
{
console.log("ERROR"+e);
}
Now i get the console output.

Show an alert or popup if a Javascript error occurs

Is it possible to get visuel notifyed if I get a Javascript error?
In developing I have Firebug or something else open so I spot it.
But in the case where I do a light demostration for someone else I can not have it open.
I still prefer to know about the error instead of it failing silently and I dont know about trailings errors where I can't distinct wish between real and trailing errors.
You can surround your code in a try-catch and call alert with the error message. For example, if your code is as follows:
var x = document.getElementById("wrong_id"); //returns null
x.innerHTML = "Hello world!"; //null exception
you can surround it with the try-catch as follows:
try {
var x = document.getElementById("wrong_id"); //returns null
x.innerHTML = "Hello world!"; //null exception
}
catch(err) {
alert(err.message);
}
err.message basically contains the error message, similar to the one you see in Firebug.
Edit: You may also define window.onerror. See this answer
I believe you can use try catch functionality to show the error.
Something like this:
try {var a = 20 / f;}
catch (err) {alert(err);}
http://jsfiddle.net/magwalls/h7kqr/
Hope this helps!

How do we track Javascript errors? Do the existing tools actually work?

Today I find the need to track and retrieve a Javascript error stacktrace to solve them.
Today we were able to capture all rest calls, the idea is that once you get an error, automatically posts the stacktrace of that error plus the responses of the rest saved services so we can detect, reproduce, and solve the problems in almost an identical environment/situation.
As a requirement we were asked to make a module that can be included without being intrusive, for example:
Include the module that contains the hook logic in one JS, would be not invasive, include several lines of code in various JS files would be invasive.
The goal is to make a tool that can be included in a system already developed and track error events (like console).
I've read about this trackers logic:
errorception.com/
trackjs.com/
atatus.com/
airbrake.io/
jslogger.com/
getsentry.com/
muscula.com/
debuggify.net/
raygun.io/home
We need to do something like that, track the error and send it to our server.
As "Dagg Nabbit" says... "It's difficult to get a stack trace from errors that happen "in the wild" right now"...
So, we got a lot of paid products, but how did they really works?
In Airbrake they use stacktrace and window.onerror:
window.onerror = function(message, file, line) {
setTimeout(function() {
Hoptoad.notify({
message : message,
stack : '()#' + file + ':' + line
});
}, 100);
return true;
};
But i cant figure out when the stacktrace really used.
At some point, stacktrace, raven.js and other trackers need try / catch.
what happens if we found a way to make a global wrapper?
Can we just call stacktrace and wait for the catch?
How can I send a stack trace to my server when an unexpected error occurs on the client? Any advice or good practices?
It's difficult to get a stack trace from errors that happen "in the wild" right now, because the Error object isn't available to window.onerror.
window.onerror = function(message, file, line) { }
There is also a new error event, but this event doesn't expose the Error object (yet).
window.addEventListener('error', function(errorEvent) { })
Soon, window.onerror will get a fifth parameter containing the Error object, and you can probably use stacktrace.js to grab a stack trace during window.onerror.
<script src="stacktrace.js"></script>
<script>
window.onerror = function(message, file, line, column, error) {
try {
var trace = printStackTrace({e: error}).join('\n');
var url = 'http://yourserver.com/?jserror=' + encodeURIComponent(trace);
var p = new printStackTrace.implementation();
var xhr = p.createXMLHTTPObject();
xhr.open('GET', url, true);
xhr.send(null);
} catch (e) { }
}
</script>
At some point the Error API will probably be standardized, but for now, each implementation is different, so it's probably smart to use something like stacktracejs to grab the stack trace, since doing so requires a separate code path for each browser.
I'm the cofounder of TrackJS, mentioned above. You are correct, sometimes getting the stack traces requires a little bit of work. At some level, async functions have to be wrapped in a try/catch block--but we do this automatically!
In TrackJS 2.0+, any function you pass into a callback (addEventListener, setTimeout, etc) will be automatically wrapped in a try/catch. We've found that we can catch nearly everything with this.
For the few things that we might now, you can always try/catch it yourself. We provide some helpful wrappers to help, for example:
function foo() {
// does stuff that might blow up
}
trackJs.watch(foo);
In latest browsers, there is a 5th parameter for error object in window.onerror.
In addEventListener, you can get error object by event.error
// Only Chrome & Opera pass the error object.
window.onerror = function (message, file, line, col, error) {
console.log(message, "from", error.stack);
// You can send data to your server
// sendData(data);
};
// Only Chrome & Opera have an error attribute on the event.
window.addEventListener("error", function (event) {
console.log(e.error.message, "from", event.error.stack);
// You can send data to your server
// sendData(data);
})
You can send data using image tag as follows
function sendData(data) {
var img = newImage(),
src = http://yourserver.com/jserror + '&data=' + encodeURIComponent(JSON.stringify(data));
img.crossOrigin = 'anonymous';
img.onload = function success() {
console.log('success', data);
};
img.onerror = img.onabort = function failure() {
console.error('failure', data);
};
img.src = src;
}
If you are looking for opensource, then you can checkout TraceKit. TraceKit squeezes out as much useful information as possible and normalizes it. You can register a subscriber for error reports:
TraceKit.report.subscribe(function yourLogger(errorReport) {
// sendData(data);
});
However you have to do backend to collect the data and front-end to visualize the data.
Disclaimer: I am a web developer at https://www.atatus.com/ where you can track all your JavaScript errors and filter errors across various dimensions such as browsers, users, urls, tags etc.
#Da3 You asked about appenlight and stacktraces. Yes it can gather full stacktraces as long as you wrap the exception in try/catch block. Otherwise it will try reading the info from window.onerror which is very limited. This is a browser limitation (which may be fixed in future).

Is there any way to get the origin of an alert box?

I work with some very large and confusing JavaScript files that I did not write. Sometimes an alert will come up but I don't know where it's coming from.
You could search all files for the text contained in the alert but if that text is dynamic it won't work.
Is there a way to set a breakpoint in order to intercept an alert?
At the very top of your HTML:
window.alert = function() {
debugger;
}
debugger is a statement that invokes any debugging functionality available. With developer tools open, you'll automatically hit a breakpoint whenever alert is called. You can then inspect the call stack to see exactly what called the custom alert function.
It may or may not be helpful to you, but you can overwrite the alert function to do whatever you want with it. For example, instead of alert boxes, you could have it log the message to the console.
window.alert = function(msg) {
console.log(msg);
}
alert('test');
I agree with Brian Glaz, but in order to get more details (line number) you might try to throw an error when alerting something and outputting the error on the console. this way, the console will point you to the right line number where the alert function was called.
Put this snippet at the top of your document and give it a try :
var originalAlert = window.alert;
window.alert = function(){
try{
throw new Error('alert was called');
} catch(e){
console.warn(e);
}
return originalAlert.apply(window, arguments);
}
Open Chrome push F12 key and go to Sources.
Then choose a script file Ctrl+F and search for alert.
You can put breakpoint on any line you wish

Categories

Resources