Node.js Debugging

Proper logging is very useful for Web applications, both during development and after deployment. The hard part is how to organize the logging code and output logs, in a nutshell: knowing where each log came from. I recently found a practical way to organize and optimize Node.js debugging.

Creating a Debug instance is simple, and you can create multiple Loggers per file:

// Create multiple instances of debug
// In theory these debug instances would serve two different purposes.
var debuggerA = require('debug') ('worker:a'),
    debuggerB = require('debug') ('worker:b');

// Sample Usages of the Debugger
function work() {
  debuggerA('doing lots of uninteresting work');
  setTimeout(work, Math.random() * 1000);
}

work();

function workb() {
  debuggerB('doing some work');
  setTimeout(workb, Math.random() * 2000);
}

workb();Copy the code

logger

You must define environment variables that are used to assign namespaces to debugger instances. When the script runs, the log should be output to STDOUT:

// Show all debugger messages prefixed "worker:_____"All debuggers are prefixed with"worker:_____")
DEBUG=worker:* node app.jsCopy the code

When using environment variables, when you only want to record certain types of messages in a development or production environment, the output log is clear. What a wise use of namespaces!

I might also use Chalk to add the color I want to the message:

var chalk = require('chalk');

debuggerA(chalk.red.bold('OMG an awful error! '));Copy the code

Debugging has a very simple purpose, to help us do things better. Don’t skimp when it comes to logging informational messages, it will help you during the development process and take a better look at yourself after a security incident!

Copyright Notice: All articles on this Blog are licensed under a CC BY-NC-SA 3.0CN license unless otherwise specified. Reprint please indicate the source!