[Record 7] Vue+node+koa2+mysql+nginx+redis, full-stack development of small programs and administrator management system projects-generating request logs

Preface: The log is a very important thing for the system. If there is a sudden error or exception in the production environment, the fastest way to quickly know where the problem has occurred is to view the system log. The log is not only used to help locate the error after the system is abnormal, but also to understand what request the user has operated. The client ip and address can be known, and the user's operation information is saved for the system administrator to view. Let's take a look at how node saves log information and provides api for front-end viewing.

Log table structure

Insert picture description here
This is one of the data tables of the database. I will save the request log information here so that the administrator can view it.

Create middleware that generates logs

//app.js
// 日志
app.use(async (ctx, next) => {
    
    
  let data = ''
  let params = {
    
    }
  if (ctx.method == 'GET' || ctx.method == 'get') {
    
    
    data = ctx.request.query
  } else if (ctx.method == 'POST' || ctx.method == 'post') {
    
     
    data=ctx.request.body
  }
  //拦截入参做安全防护
  await common.safety((ctx.method == 'GET' || ctx.method == 'get') ? 	  ctx.request.query : (ctx.method == 'POST' || ctx.method == 'post') ? ctx.request.body : {
    
    })
  const start = new Date()
  await next()
  const ms = new Date() - start
  params.ms = ms
  params.ip = await common.getClientIP(ctx.req)
  let address = (await common.getClientAddress(params.ip)).body
  params.address='局域网'
  if (address.status == 1&&(address.province.length||address.city.length)) {
    
     
    params.address=address.province+address.city
  }
  params.url = ctx.url
  params.method = ctx.method
  params.params = JSON.stringify(data)
  let flag = false
  whiteList.noLogger.map(res => {
    
     
    if (ctx.url.indexOf(res) !== -1) {
    
    
      flag = true
    }
  })
  if (!flag) {
    
     
    await api.loggerData(params)
  }
  console.log(`${
     
     ctx.method} ${
     
     ctx.url} - ${
     
     ms}ms`)
})

Security issues are used here to verify input parameter data; such as keywords, anti-script injection, anti-scrf, etc.

//getClientIP方法
  //获取用户的真实地址
  async getClientIP(req) {
    
    
    return (req.headers['x-forwarded-for'] || // 判断是否有反向代理 IP
      req.connection.remoteAddress || // 判断 connection 的远程 IP
      req.socket.remoteAddress || // 判断后端的 socket 的 IP
      req.connection.socket.remoteAddress).replace(/::ffff:/, '')
  }

This is used to obtain the ip address of the client's api. ⚠️: The LAN is 127.0.0.1

Get geographic location based on ip address

//getClientAddress方法
//根据ip地址获取用户的地理位置
  async getClientAddress(ip) {
    
     
    let option = {
    
    
      method: 'get',
      // &key 不能写成?key
      url: `https://restapi.amap.com/v3/ip?parameters&key="您的key值"&ip=${
     
     ip}`
    }
    return await koa2Req(option)
  }

Insert picture description here

Obtaining the client's geographic location based on the ip address is a third-party service provided by Tencent. If you don’t understand, you can look at => IP positioning

After completing the above, you can insert the acquired data into the log table.

//api.js
//生成请求日志
  loggerData: async (params) => {
    
    
    let id = common.formatDateTime(new Date(),'orderId')+Math.ceil((Math.random() + 1) * 1000)
    let nowtime = await common.formatDateTime(new Date())
    let add_sql = `insert into logger (id,ip,address,method,params,url,ms,createtime) values(${
     
     id},'${params.ip}','${params.address}','${params.method}','${params.params}','${params.url}','${params.ms}','${nowtime}')`
    await allServices.query(add_sql)
  }

At this point, all operations of the system log are completed. When the front end needs to view, it provides an api to get the table data and return it. The next section will introduce the timing tasks that front-end people can play.

Previous: Server-side image upload and download
Next: Use timed tasks to execute scripts

Guess you like

Origin blog.csdn.net/Smell_rookie/article/details/108965115