morgan 是nodejs的一个日志模块,由 express 团队维护。
这里通过示例简要介绍morgan模块在express中的应用,大部分示例直接来自于 morgan的文档 。
首先需要安装morgan模块:
$ npm install morgan --save
morgan的API:
morgan(format, options);
其中 format
表示日志的格式, morgan预定义了一些日志格式,用常量字符串表示,如’combined’, ‘common’, ‘short’, ‘dev’等;options表示选项,比如将日志输出到终端或者文件,这个参数是可选的。
format
为’combined’时的日志样例:
::1 - - [28/Aug/2016:10:50:53 +0000] "GET /home HTTP/1.1" 200 10 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36"
format
为’short’时的日志样例:
::1 - GET /home HTTP/1.1 304 - - 3.345 ms
var express = require('express'); var morgan = require('morgan'); var app = express(); app.use(morgan('short')); // app.use(morgan('short', {stream: process.stdout})); // ::1 - GET /home HTTP/1.1 304 - - 3.345 ms app.get('/to-stdout', function(req, res, next) { res.send('done.'); }); app.listen(3000);
morgan(format, options)
的第二个参数省略时,morgan默认将日志输出到终端,所以第二个参数的值默认为: {stream: process.stdout}
。
var express = require('express'); var morgan = require('morgan'); var fs = require('fs'); var path = require('path'); var app = express(); var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log')); app.use(morgan('common', {stream: accessLogStream})); app.get('/to-file', function(req, res) { res.send('done!'); }); app.listen(3000);
需要定义 morgan(format, options)
的第二个参数,表示文件输出流。
var express = require('express'); var morgan = require('morgan'); var fs = require('fs'); var path = require('path'); var fileStreamRotator = require('file-stream-rotator'); var app = express(); var logDir = path.join(__dirname, 'logs'); // ensure log directory exists fs.existsSync(logDir) || fs.mkdirSync(logDir); // create a rotating write stream var accessLogStream = fileStreamRotator.getStream({ date_format: 'YYYYMMDD', filename: path.join(logDir, 'access-%DATE%.log'), frequency: 'daily', verbose: true }); app.use(morgan('common', {stream: accessLogStream})); app.get('/to-rotate-file', function(req, res) { res.send('done!'); }); app.listen(3000);
需要用到 file-stream-rotator
模块来创建一个轮转的文件流。
同时加载输出到终端和文件的morgan对象,如:
app.use(morgan('combined')); app.use(morgan('common', {stream: accessLogStream}));
var express = require('express'); var morgan = require('morgan'); var uuid = require('node-uuid'); morgan.token('id', function(req) { return req.id; }); function assignId(req, res, next) { req.id = uuid.v4(); next(); }; var app = express(); app.use(assignId); app.use(morgan(':id :method :url :response-time ms')); app.get('/customized-format', function(req, res) { res.send('done!'); }); app.listen(3000);
使用uuid标识每一个请求,日志如下:
a08516c4-201a-4d8a-9f22-d1b6de5e225f GET /customized-format 3.118 ms