手动搭建koa+ts项目框架(日志篇)

文章目录

前言

本文基于手动搭建koa+ts项目框架(路由篇)新增日志记录


一、安装koa-logger

bash 复制代码
npm i -S koa-onerror
and 
npm i -D @types/koa-logger

二、引入koa-logger并使用

./src/index.ts文件引入

ts 复制代码
import Koa from "koa";

import logger from 'koa-logger'

import index from "./routes/index"
import users from "./routes/user"

const app = module.exports = new Koa();

// 中间件
app.use(logger())

// 日志记录
app.use(async (ctx, next) => {
    const start = new Date()
    await next()
    const ms = Number(new Date()) - Number(start)
    console.log(ctx.query)
    console.log(ctx.body)
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// 接口路由
app.use(index.routes())
app.use(users.routes())

if (!module.parent) app.listen(3000);

执行npm run dev开启服务,使用postman查看相关接口

如图,打印了调用的接口项目信息(可以根据项目需要,记录相关日志到数据库啦)


总结

根据koa-logger依赖,可记录实际用户访问的接口记录~

如有启发,可点赞收藏哟~

相关推荐
coderCN14 小时前
Nodejs 响应头和请求头
后端·node.js
__zRainy__16 小时前
Node系列 · ORM:log4js 日志记录
node.js·log4j
秋秋小事1 天前
node 导入与导出
node.js
秋秋小事1 天前
node event模块
node.js
晴天161 天前
Node.js 中 `npm install` 命令分析-Day30
前端·npm·node.js
晴天161 天前
VS Code `launch.json` 指南(Node.js版)-Day30
node.js·json
空の鱼2 天前
Mac 上 Node 版本管理(brew + nvm 共存方案)
macos·node.js
请你吃div2 天前
Node 后端项目 Docker 自动部署教程(GitHub + 宝塔 + Self-hosted Runner)
后端·docker·node.js
泠曦れいひ2 天前
在当前项目中安装Vite
前端框架·npm·node.js
Joseph 乔2 天前
【NVM】node 和 nvm 卸载(安装 node & nvm & npm & cnpm & yarn 及配置)
npm·node.js