Koa2 is really a very lightweight framework. Both the lightweight and routing are separate modules. Koa2 also has no logging function. If we need to have some requested logs and time, we need to introduce log middleware
Introducing time format library MomentJS
Install MomentJS
npm install moment --save
Simple format time
Use YYYY-MM-DD HH:MM:SS to represent year month day hour minute second (24-hour system)
console.log(Moment().format('YYYY-MM-DD HH:MM:SS'));
output
2019-05-01 20:05:95
Using Koa2 log Middleware
Install koa logger
npm install koa-logger --save
If you need to use ts, you need to install the TS type declaration
npm install @types/koa-logger --save
Simple use of KOA logger
const Koa = require("koa"); const Koa_Logger = require("koa-logger"); // Log Middleware const Koa_Router = require("koa-router"); // instantiation const app = new Koa(); const logger = Koa_Logger(); const router = new Koa_Router(); router.get("/",async (ctx)=>{ ctx.body = "Hellow Koa"; }); // Using middleware app.use(logger); // Log output app.use(router.routes()); // Route // Start app app.listen(3000); // Set listening port // Startup ID console.log("Koa Run in: http://127.0.0.1:3000");
Visit http://localhost:3000/ , page display
console output
Add time to request log
Change the calling method of logger and add the time after the moment format
const Koa = require("koa"); const Koa_Logger = require("koa-logger"); // Log Middleware const Koa_Router = require("koa-router"); const Moment = require("moment"); // instantiation const app = new Koa(); const logger = Koa_Logger((str) => { // Using log Middleware console.log(Moment().format('YYYY-MM-DD HH:MM:SS')+str); }); const router = new Koa_Router(); router.get("/",async (ctx)=>{ ctx.body = "Hellow Koa"; }); // Using middleware app.use(logger); // Log output app.use(router.routes()); // Route // Start app app.listen(3000); // Set listening port // Startup ID console.log("Koa Run in: http://127.0.0.1:3000");
Separate visits http://localhost:3000/
,http://localhost:3000/?test
The console output is as follows
So we have a request log with time