参考地址
morgan
是express
默认的日志中间件,也可以脱离express
,作为node.js的日志组件单独使用。
项目中应用场景
1.首先安装morgan
以及file-stream-rotator
cnpm i morgan file-stream-rotator -S
2.其次Demo代码如下
logsModel.js
/**
* 日志记录
*/
const mongoose = require('../common/db').mongoose;
const linkMongo = require('../common/db').linkMongo;
const schema = {
ip: {type: String, required: false}, // 访问者的ip
method: {type: String, required: false}, // 调用方法
time: {type: Number, required: false}, // 响应时间
code: {type: Number, required: false}, // 状态码
}
const collectionName = 'logs';
const LogSchema = mongoose.Schema(schema);
const Logs = linkMongo.model(collectionName, LogSchema);
module.exports = Logs;
app.js
/**
* 简单Demo
*/
const restify = require('restify');
const redis = require('redis');
const morgan = require('morgan');
const server = restify.createServer({
name: 'demo',
version: '1.0.0'
});
//日志系统Demo
const FileStreamRotator = require('file-stream-rotator');
const fs = require('fs');
const path = require('path');
const logDirectory = path.join(__dirname, 'log');
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory)
let accessLogStream = FileStreamRotator.getStream({
date_format: 'YYYYMMDD',
filename: path.join(logDirectory, '日志-%DATE%.log'),
frequency: 'daily',
verbose: false
})
server.use(morgan(function (tokens, req, res) {
//这里记录日志 可以选择响应时间大于1秒 或者状态码不是200的时候的数据
const LogsModel = require('./models/logs');
const data = {
ip: '',
method: tokens.method(req, res),
time: tokens['response-time'](req, res),
code: tokens.status(req, res),
};
LogsModel.create(data); // 这里可用于存入数据库
return [
`状态码: ${tokens.status(req, res)}`,
`响应时间: ${tokens['response-time'](req, res)}ms`
].join(' ')
}, {stream: accessLogStream})); // 这里可以写入日志
server.use(restify.plugins.acceptParser(server.acceptable));
server.use(restify.plugins.queryParser());
server.use(restify.plugins.bodyParser());
server.listen('3000', '0.0.0.0', function () {
console.log('本地端口监听:','3000');
});
const routes = require('./routes')(server);
这样一个简单的Demo完成了。