nodejs日志管理工具包:log4js 和 winston
1、log4js的使用
1)、package.json中加入依赖
"log4js":"~0.6.21"
2)、log4js的配置文件log4js_conf.json
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');
}