发布时间:2019-07-10编辑:佚名阅读(2230)
http 请求日志记录中间件,详细请参考:(https://github.com/expressjs/morgan)
npm install express morgan
注:执行上面命名时应先安装express,详细参考:node快速构建express项目
var express = require('express'); var app = express(); var morgan = require('morgan'); app.use(morgan('short')); app.use(function(req, res, next){ res.send('ok'); }); app.listen(3000);
node bin\www 运行程序,并在浏览器里访问 http://127.0.0.1:3000
控制台即可看到打印的日志如下:
::ffff:127.0.0.1 - GET / HTTP/1.1 304 - - 3.019 ms ::ffff:127.0.0.1 - GET /favicon.ico HTTP/1.1 200 2 - 0.984 ms
morgan支持stream配置项,可以通过它来实现将日志写入文件便于查看。示例如下:
var express = require('express'); var app = express(); var morgan = require('morgan'); var fs = require('fs'); var path = require('path'); var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), {flags: 'a'}); app.use(morgan('short', {stream: accessLogStream})); app.use(function(req, res, next){ res.send('ok'); }); app.listen(3000);
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var FileStreamRotator = require('file-stream-rotator') var path = require('path') var fs=require('fs'); var logDirectory = path.join(__dirname, 'logs') var index = require('./routes/index'); var users = require('./routes/users'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // ensure log directory exists fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory) // create a rotating write stream var accessLogfile = FileStreamRotator.getStream({ date_format: 'YYYY-MM-DD', filename: path.join(logDirectory, 'access-%DATE%.log'), frequency: 'daily', verbose: false }) var errorLogfile = FileStreamRotator.getStream({ date_format: 'YYYY-MM-DD', filename: path.join(logDirectory, 'error-%DATE%.log'), frequency: 'daily', verbose: false }) // 对Date的扩展,将 Date 转化为指定格式的String // 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符, // 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字) // 例子: // (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 // (new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18 Date.prototype.Format = function (fmt) { //author: meizz var o = { "M+": this.getMonth() + 1, //月份 "d+": this.getDate(), //日 "h+": this.getHours(), //小时 "m+": this.getMinutes(), //分 "s+": this.getSeconds(), //秒 "q+": Math.floor((this.getMonth() + 3) / 3), //季度 "S": this.getMilliseconds() //毫秒 }; if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); return fmt; } // 自定义token logger.token('from', function(req, res){ return JSON.stringify(req.query) || '-'; }); logger.token('time', function(req, res){ return new Date().Format("yyyy-MM-dd hh:mm:ss"); }); logger.token('nextROw', function(req, res){ return "\r\n"; }); // 自定义format,其中包含自定义的token logger.format('joke', '[joke] :time :remote-addr :remote-user :method :url :from :status :referrer :response-time ms :user-agent :nextROw'); //跳过不需要记录的请求 function skip (req) { return (req.url).indexOf('stylesheets') != -1 } // 使用自定义的format app.use(logger('joke')); app.use(logger('joke',{skip: skip, stream: accessLogfile })); //打印到日志文件中 app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', index); app.use('/users', users); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handler app.use(function(err, req, res, next) { var now = new Date(); var time = now.getFullYear() + '-' + now.getMonth() + '-' + now.getDate() + ' ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds(); var meta = '[' + time + '] '+req.method+' ' + req.url + '\r\n'; errorLogfile.write(meta + err.stack + '\r\n\r\n\r\n'); next(); // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); module.exports = app;
关键字: Express 中间件 morgan logger
1人
0人
1人
0人