文章目录
个人博客网站:https://blog.crazymad.top
koa使用自定义日志中间件
注明:本样例程序运行在koa^2.5.3版本上
项目结构
|- package.json
|- node_modules
|- logs // 运行日志目录
|- access.log
|- src // 源码文件目录
|- config // 配置文件目录
|- baseConfig.js // 通用配置文件
|- controller // 路由文件目录
|- testRouter.js // 测试用的路由文件
|- lib // 自定义模块目录
|- requestLog.js
|- app.js // 程序入口文件
程序入口 /src/app.js
const koa = require('koa') // koa核心模块
const Router = require('koa-router') // 路由模块
const LoggerFactory = require('./lib/requestLog') // 日志模块
const config = require('./config/baseConfig') // 配置文件模块
const router = new Router() // 为了方便测试,就不专门写路由文件了,直接在app.js里面写路由
router.get('/test', (ctx, next) => { // 测试用的路由
ctx.body = 'hello world'
})
var app = new koa()
// 使用日志中间件,需要放在router前面
app.use(LoggerFactory.getLogger(config))
// 使用路由模块
app.use(router.routes()).use(router.allowedMethods())
app.listen(8085);
通用配置模块 /src/config/baseConfig.js
const path = require('path')
var config = {
// 基本路径配置
base: {
// 项目工作目录绝对路径
workDir: path.join(__dirname, '../../'),
// 源码目录绝对路径
srcDir: path.join(__dirname, '../')
},
// 日志路径配置
log: {
// 日志文件夹绝对路径
logDir: path.join(__dirname, '../../logs'),
// 日志文件相对路径
accessLogFile: 'access.log'
}
}
module.exports = config
日志中间件模块 /src/lib/requestLog.js
const fs = require('fs')
const path = require('path')
class LoggerFactory {
// 由外部传入的配置决定日志文件的位置
static getLogger(config) {
// http请求日志输出文件绝对路径
var accessLogFile = path.join(config.log.logDir, config.log.accessLogFile)
// 返回中间件处理函数
return async function log(ctx, next) {
const start = Date.now()
const requestTime = new Date()
return next().then(() => {
const ms = Date.now() - start
const clientIp = ctx.request.ip.match(/([0-9]{1,3}\.){3}[0-9]{1,3}/g)[0]
let logout = `${clientIp} -- ${requestTime} -- ${ctx.method} -- ${ctx.url} -- ${ms}ms`
// 命令行模式下向终端输出日志
console.log(logout)
// 输出日志文件
fs.appendFileSync(accessLogFile, logout + '\n')
})
}
}
}
module.exports = LoggerFactory
样例输出 /logs/access.log
127.0.0.1 -- Mon Oct 08 2018 23:04:51 GMT+0800 (中国标准时间) -- GET -- /test -- 29ms
127.0.0.1 -- Mon Oct 08 2018 23:04:53 GMT+0800 (中国标准时间) -- GET -- /test -- 3ms
127.0.0.1 -- Mon Oct 08 2018 23:04:53 GMT+0800 (中国标准时间) -- GET -- /test -- 1ms
更多博客请关注个人博客网站:https://blog.crazymad.top