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‘); }
时间: 2024-10-14 06:39:35