本文摘录自《Nodejs学习笔记》,更多章节及更新,请访问 github主页地址。欢迎加群交流,群号 197339705。javascript
在node程序开发中时,常常须要打印调试日志。用的比较多的是debug模块,好比express框架中就用到了。下文简单举几个例子进行说明。文中相关代码示例,可在这里找到。html
备注:node在0.11.3版本也加入了util.debuglog()用于打印调试日志,使用方法跟debug模块大同小异。java
首先,安装debug
模块。node
npm install debug复制代码
使用很简单,运行node程序时,加上DEBUG=app
环境变量便可。git
/** * debug基础例子 */
var debug = require('debug')('app');
// 运行 DEBUG=app node 01.js
// 输出:app hello +0ms
debug('hello');复制代码
当项目程序变得复杂,咱们须要对日志进行分类打印,debug支持命令空间,以下所示。github
DEBUG=app,api
:表示同时打印出命名空间为app、api的调试日志。DEBUG=a*
:支持通配符,全部命名空间为a开头的调试日志都打印出来。/** * debug例子:命名空间 */
var debug = require('debug');
var appDebug = debug('app');
var apiDebug = debug('api');
// 分别运行下面几行命令看下效果
//
// DEBUG=app node 02.js
// DEBUG=api node 02.js
// DEBUG=app,api node 02.js
// DEBUG=a* node 02.js
//
appDebug('hello');
apiDebug('hello');复制代码
有的时候,咱们想要打印出全部的调试日志,除了个别命名空间下的。这个时候,能够经过-
来进行排除,以下所示。-account*
表示排除全部以account开头的命名空间的调试日志。express
/** * debug例子:排查命名空间 */
var debug = require('debug');
var listDebug = debug('app:list');
var profileDebug = debug('app:profile');
var loginDebug = debug('account:login');
// 分别运行下面几行命令看下效果
//
// DEBUG=* node 03.js
// DEBUG=*,-account* node 03.js
//
listDebug('hello');
profileDebug('hello');
loginDebug('hello');复制代码
debug也支持格式化输出,以下例子所示。npm
var debug = require('debug')('app');
debug('my name is %s', 'chyingp');复制代码
此外,也能够自定义格式化内容。api
/** * debug:自定义格式化 */
var createDebug = require('debug')
createDebug.formatters.h = function(v) {
return v.toUpperCase();
};
var debug = createDebug('foo');
// 运行 DEBUG=foo node 04.js
// 输出 foo My name is CHYINGP +0ms
debug('My name is %h', 'chying');复制代码
debug:github.com/visionmedia…
debuglog:nodejs.org/api/util.ht…bash