永遠的Console Log不會是一個聰明程式設計師的選擇
Node.js的一套log套件,可以讓程式裡面的Log機制表達更完整
他包含可以針對log分等級、分類、建立不同形式的log(console, file, mail...)、幫你切割log大小、幫你House Keeping...
其中等級部分:
TRACE > DEBUG > INFO > WARN > ERROR > FATAL
其中,TRACE為最囉唆模式,顯示的LOG會包含Debug, Info, Warn, Error, Fatal等,越往右邊,所包含顯示項目越少...
下面是使用上的一些紀錄:
Install:
# npm install log4js
npm http GET https://registry.npmjs.org/log4js
npm http 304 https://registry.npmjs.org/log4js
npm http GET https://registry.npmjs.org/async/0.1.15
npm http 304 https://registry.npmjs.org/async/0.1.15
log4js@0.5.6 ../node_modules/log4js
└── async@0.1.15
File: logger.js
/**
* Usage:
* var logger = require('./logger').getInstance();
* logger.debug('TEST...123');
*/
var log4js = require('log4js')
, logger = log4js.getLogger()
, logFile = process.env.LOGPATH ? process.env.LOGPATH : '/tmp/node.log'
, logCategory = process.env.LOGCATG ? process.env.LOGCATG : 'normal'
, logLevel = process.env.LOGLEVEL ? process.env.LOGLEVEL : 'DEBUG'
, logMaxSize = process.env.LOG_MAX_SIZE ? process.env.LOG_MAX_SIZE : 20480
, logBackup = process.env.LOG_BACKUP ? process.env.LOG_BACKUP : 7;
log4js.configure(
{
"appenders": [
{ type: 'console' },
{
"type": "file",
"filename": logFile,
"maxLogSize": logMaxSize,
"backups": logBackup,
"category": logCategory
}
]
}
);
var logger = log4js.getLogger(logCategory);
logger.setLevel(logLevel);
exports.getInstance = function() {
return logger;
}
File: test.js
var logger = require('./logger').getInstance();
logger.trace('[trace]....');
logger.debug('[debug]....');
logger.info('[info]....');
logger.warn('[warn]....');
logger.error('[error]....');
logger.fatal('[fatal]....');
執行上,針對不同等級,有使用不同顏色來表示,上面程式將log以環境變數來設定,如果設定上環境變數,就可以清楚知道Log的等級:
Trace mode:
Debug mode:
Info mode:
Warn mode:
Error mode:
Factal mode: