gaozhlzh 2015-08-02
Nodejs日志管理工具包:log4js 和 winston
1、log4js的使用
1)package.json中加入依赖
"log4js":"~0.6.21"
2)写一个log4js的配置文件log4js_conf.json
{
"appenders": [
{
"type": "console"
},
{
"type": "file",
"filename": "logs/access.log",
"maxLogSize": 1024,
"backups": 3,
"category": "normal"
}
]
}
3)写一个工具类log4js-utils.js
var log4js = require('log4js');
/**
log4js.configure({
appenders: [
{ type: 'console' },
{ type: 'file', filename: 'logs/access.log', category: 'normal' }
]
});
*/
log4js.configure('E:/Node/file-server/config/log4js_conf.json');
exports.logger = function(){
var logger = log4js.getLogger('normal');//获取配置文件中category为normal的appender
logger.setLevel('DEBUG');
return logger;
}
4)在其他需要使用日志的地方引入工具类
var logger = require('../utils/log4js-utils').logger();
exports.index = function(req,res) {
logger.debug('debug');
logger.info('info');
logger.warn('warn');
logger.error('error');
res.send('ok');
}
2、winston
winston的使用也很简单,不多说。
var winston = require('winston');
exports.logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)(),
new (winston.transports.File)({ filename: 'logs/all.log' })
],
exceptionHandlers: [
new winston.transports.File({ filename: 'logs/exceptions.log' })
],
exitOnError:false
});
var logger = require('../utils/winston-utils').logger;
exports.index = function(req,res) {
logger.log('error', "log");
logger.info("info");
logger.warn("warn");
logger.error("error");
res.send('ok');
}
下面的内容你可能也喜欢:
Node.js 的详细介绍:请点这里
Node.js 的下载地址:请点这里
Node端的日志插件Log4js,以后版本更新了继续跟进安装&&版本npm install log4js. "log4js": "2.9.0",最简单的写法var log4js = require;a