CLOSE ×
Get in Touch
Thank you for your interest! Please fill out the form below, and I will do my best to get back to you.

Thank you! Your submission has been received!

Oops! Something went wrong while submitting the form.

Debug Logging in JavaScript

Garth Henson
|
JavaScript
|
30 Mar 2011

So, one of the repeat topics I’ve heard in JavaScript discussions both internal and external to work is that of tracing and logging JavaScript activities. What is the best way? How do you know in what order your code is actually completing? These are all valid concerns, and thankfully, there is a fairly easy way to help yourself out. There are back-end libraries to assist with this type of logging such as Apache’s log4j – which has been ported to other popular languages like PHP and C++, but what about seeing under the hood of your browser run scripts?

There is an available logging mechanism called FVLogger that does some pretty interesting things, and I’d recommend you do a little reading on implementing it for any advanced logging needs you have. But how about simple output? What if we want to alert on specific actions without interrupting the processing of the page? Well, thanks to the built-in console object available in Firefox, we can resort to some default behavior in a simplistic logging object.

Consider the following object:

Very simply, this is checking the context of the logger at instantiation and defining its log message accordingly. If a div ID is provided in which to render the logs, that action will be taken. Otherwise, we try to write to the console, if it exists. Finally, if there is nothing we can do, we go ahead and declare an empty function for log to avoid any JavaScript errors being thrown. Now, to see our logger at work, all we have to do is instantiate it, set a global DEBUG variable and use logger.log() on anything we want to trace:

What’s great about addressing the contextual issue in this way is that we can easily expand to attempt any number of executions of the logging mechanism in whatever priority we would like. Further, by declaring the definition of the action based on context at the time of the object’s instantiation, we can avoid costly context checks every time a method is invoked – something that should probably be visited within a couple popular JavaScript libraries.

Of course, while the code above is useful, it is nowhere near robust enough for full development. We would really want to consider defining methods for things such as info(), debug() and warn() for starters. With a few more customizations and possibly accounting for some more output options, we could have a fairly significant logger on our hands.

Garth Henson
Garth is as a lead engineer at The Walt Disney Company, specializing in JavaScript applications.

Recent Blog Posts

Let's Work Together
Contact Me