koa使用自定义日志中间件

个人博客网站: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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值