This is the 10th day of my participation in Gwen Challenge

Lynne, a front-end development engineer who can cry, love and laugh forever. In the Internet wave, love life and technology.

preface

To implement a KOA middleware, first you need to understand middleware, as we saw yesterday, and second you need to understand KOA.

Today, we will start with an understanding of KOA and analyze an implementation of KOA middleware based on logging middleware as an example. As you may have noticed, log4js is not for nothing!

KOA concept

Understand KOA from middleware

KOA, or the Onion model. If you think of each onion ring as a piece of middleware, each middleware will be executed twice each time a request comes in.

As shown in the following code:

Const Koa = require(" Koa ") const app = new Koa() next) => { console.log("A1") await next() console.log("A2") }); Use (async (CTX, next) => {console.log("B1") await next() console.log("B2")}); Use (async (CTX, next) => {console.log("C1") await next() console.log("C2")}); app.listen(3000); A1 -> B1 -> C1 -> C2 -> B2 -> A2Copy the code

KOA implementation principle

So what do we need to do to get the onion ring running like the one above?

  • First we need to know the array collection of the current middleware
  • Then build a composition method, combine these middleware according to the onion structure, and execute
Use = (fn) => {this.middleware.push(fn) return this} // compose compose function compose (Middleware) {// context: next: Return function (context, next) {function dispatch (I) {index = I // middleware let fn = middleware[I] if (! Resolve () {// If dispatch(0) initiates the execution of the first middleware A, B, and C, next will execute as Dispatch (1). Resolve () // The innermost middleware C is await next(). Resolve // Middleware B starts console.log("B2") // Likewise, Log ("A2") return promise. resolve(fn(context, () => { return dispatch(i + 1) })) } catch (err) { return Promise.reject(err) } } return dispatch(0) } }Copy the code

Koa constructed the middleware execution structure of the Onion ring by passing the next parameter in the middle of the middleware and combining the middleware array and the compose combination function. This is why the Onion ring middleware mechanism works.

Implement a KOA middleware using the KOA middleware mechanism

The premise

  • Understand the use of log4JS -> Log advanced log4js is not completely explained

  • Understand the principle and use of middleware — nodeJS learning middleware

Log middleware implementation preparations

For a server application, the record of the log is essential, we need to use it to record what the project program did every day, when the error occurred, what error occurred and so on, so as to facilitate the future review, real-time grasp of the running status of the server, restore the problem scene.

So you need to:

Install log4JS NPM I log4js-s

Set the information segment to be logged (log_info.js)

Export default (CTX, message, commonInfo) => {const {method, // request method url, Headers} = ctx.request; Const client = {method, url, host, message: headers['referer'], Return JSON. Stringify (Object.assign(commonInfo, client)); }Copy the code

Get the configured log4JS object (Logger.js)

Const getLog = ({env, appLogLevel, dir}, name) => {//log4js Appenders Custom select Let appenders = {// Custom configuration item 1 cheese: {type: 'dateFile', // Output log type filename: '${dir}/task ', // Output log path pattern:' -YYYY-MM-dd. log', // Log file suffix (task-03-08.log) alwaysIncludePattern: If true}} / / for the development environment configuration on the console print information if (env = = = "dev" | | env = = = "local" | | env = = = "development") {/ / custom configuration items 2 appenders. Out = {type: "stdout"}} // log4js set let config = {appenders, // as getLogger to get the key name of the log object, default to use categories: {default: {appenders: object. keys(appenders), // Get all appenders configuration items. AppLogLevel}}} log4js.configure(config) return log4js.getLogger(name) Default appenders (yyyYMMDd-out.log);}Copy the code

conclusion

Today we talked about the logging middleware setup information section and get configured log4JS objects, continue tomorrow!