node.js 调试
Proper logging is of massive utility for web apps, both during development and after deployment. What can sometimes be difficult is organizing both the code and output of logging, i.e. knowing where each log message is coming from. I recently found debug
, a Node.js utility for organized and optimized debugging.
在开发过程中和部署之后,正确的日志记录对于Web应用程序都具有巨大的实用性。 有时可能困难的是同时组织日志记录的代码和输出,即了解每个日志消息的来源。 我最近发现debug
,这是一个用于组织和优化调试的Node.js实用程序。
Creating an instance of debug
is simple and you can create multiple loggers per file:
创建debug
实例非常简单,您可以为每个文件创建多个记录器:
// Create multiple instances of debug
// In theory these 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();
The namespace given to a debug
instance as you must use an environment variable to signal which loggers should go to STDOUT when the script is run:
为debug
实例指定的名称空间,因为您必须使用环境变量来指示在运行脚本时哪些记录程序应转到STDOUT:
// Show all debugger messages prefixed "worker:_____"
DEBUG=worker:* node app.js
The environment variable strategy for signaling which instances should output is brilliant as you may want only certain types of messages logged in production vs. development. Use namespaces wisely!
用于发信号通知哪些实例应输出的环境变量策略非常出色,因为您可能只希望在生产与开发中记录某些类型的消息。 明智地使用名称空间!
I was also able to use chalk
to color messages as desired:
我还能够使用chalk
根据需要为消息着色:
var chalk = require('chalk');
debuggerA(chalk.red.bold('OMG an awful error!'));
debug
is one of those utilities that has a very simple purpose and accomplishes the task well. Don't skimp when it comes to logging informative messages -- they'll help you during development and could be critical when auditing the app after a security incident!
debug
是目的非常简单并且可以很好地完成任务的实用程序之一。 在记录信息性消息时请不要大惊小怪-它们会在开发过程中为您提供帮助,并且在安全事件后审核应用程序时可能至关重要!
node.js 调试