B.1. Logging

Logging helps you understand what functions and middleware are being run, shows you what errors your application is producing, and provides better insight into what’s going on in your application.

The console module is a core Node.js module and a global object, which means that you can access the console keyword anywhere in your application code. When you run console.log(), passing some message as a string of text, the output typically is printed in a terminal window or a file. For the purposes of this book, the console module offers the right logging tools for dissecting your application code. Aside from the logging tips in lesson 2, a few logging commands are important to keep in mind.

The console module has two outputs: standard and error. Although both of these outputs show text in your terminal window, they behave differently in a browser console. The next listing shows some of the other logging functions you can use with console.

Listing B.1. Using logging functions
console.log("Standard output log message");       1
console.error("Error output log message");        2
console.info("Standard output log message");      3
console.warn("Error output log message");         4

  • 1 Prints a log message to your console
  • 2 Prints a log message using the error output
  • 3 Prints a log message as an alias for console.log
  • 4 Prints a log message as an alias for console.error

In a Node.js application, these four functions behave similarly on the server. When you use these logging functions in client-side JavaScript, you’ll notice that your browser’s console window prints your log messages in formats that correspond to the message type. Warning messages have an orange background, for example, and error messages appear in red.

Two other functions that you may find useful are console.time and console.timeEnd. These two functions can be used in tandem to log the time it takes between the beginning and end of certain operations in your code. The text within these functions needs to match for the timer to work. In the next listing, function xyz takes one second and then logs a message. The resulting time for this operation logs slightly more than one second.

Listing B.2. Logging time of an operation
console.time("function xyz");            1
(function xyz() {
  setTimeout(function() {
    console.log("prints first");         2
    console.timeEnd("function xyz");     3
  }, 1000);
})();

  • 1 Starts the console timer
  • 2 Prints the console.log message as part of the function operation
  • 3 Records time at the end

console.log will become one of your best friends in web development, as log notes help you find bugs. Get to know your new friend with a little practice and variation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset