This is the 30th day of my participation in the Wenwen Challenge

Write the log

Create SRC /logs folder and create three log files: access.log, error.log, and event.log

New utils/log.js write encapsulated logging methods

utils/log.js

const fs = require('fs')
const path = require('path')

/ / write logs
function writeLog(writeStream, log) {
  writeStream.write(log + '\n')}// Generate a write Stream
function createWriteStream(fileName) {
  const fullFileName = path.join(__dirname, '.. / '.'logs', fileName)
  const writeStream = fs.createWriteStream(fullFileName, {
    flogs: 'a'
  })
  return writeStream
}

// Write access logs
const accessWriteStream = createWriteStream('access.log')
function access(log) {
  writeLog(accessWriteStream, log)
}
module.exports = {
  access
}

Copy the code

And then introduce it

app.js

.const {access}  = require('./src/utils/log')...const serverHandle = (req, res) = > {
  // Log access
  access(`${req.method} -- ${req.url} -- ${req.headers['user-agent']} -- The ${Date.now()}`)
  // Set the return format
  res.setHeader('Content-Type'.'application/json')

  / / get the path
  const url = req.url
  req.path = url.split('? ') [0]

  / / query
  req.query = querystring.parse(url.split('? ') [1])

  / / cookie
  req.cookie = {}
  const cookieStr = req.headers.cookie || ' '
  cookieStr.split('; ').forEach(item= > {
    if(! item) {return
    }
    console.log('item: ', item);
    const arr = item.split('=')
    const key = arr[0].trim()
    const val = arr[1].trim()
    req.cookie[key] = val
  })
  console.log('req.cookie', req.cookie);
  // Parse session using redis
  let needSetCookie = false // Whether to Set set-cookie. The default value is false
  let userId = req.cookie.userId // Get the userId in req
  console.log('userId', req.cookie.userId);
  // Handle the presence or absence of userId separately
  if(! userId) { needSetCookie =true // Enable Cookie setting on the server
    userId = `The ${Date.now()}_The ${Math.random()}` // Randomly generate the userId
    // Initialize the session value in redis
    set(userId, {})
  }
  / / get the session
  req.sessionId = userId / / set the req. SessionId
  get(req.sessionId)
    .then(sessionData= > {
      console.log('sessionData',sessionData);
      // debugger
      // Redis sessionData is null
      if (sessionData == null) {
        // Initialize the session value in redis
        set(req.sessionId, {})
        / / set the session
        req.session = {}
      } else {
        req.session = sessionData
      }
      / / postData processing
      return getPostData(req)
    })
    .then(postData= > {
      req.body = postData
      // Handle old blog routes

      // const blogData = handleBlogRouter(req, res)
      // if (blogData) {
      // res.end(JSON.stringify(blogData))
      // return
      // }

      // Handle blog routing
      const blogResult = handleBlogRouter(req, res)
      if (blogResult) {
        blogResult.then(blogData= > {
          // Set set-cookie when needSetCookie is true after routing
          if (needSetCookie) {
            res.setHeader('Set-Cookie'.`userId=${userId}; path=/; httponly; expires=${getCookieExpires()}`)
            needSetCookie = false
          }
          res.end(JSON.stringify(blogData))
        })
        return
      }

      // Process the user route
      // const userData = handleUserRouter(req, res)
      // if (userData) {
      // res.end(JSON.stringify(userData))
      // return
      // }
      const userResult = handleUserRouter(req, res)
      if (userResult) {
        userResult.then(userData= > {
          // Set set-cookie when needSetCookie is true after routing
          if (needSetCookie) {
            res.setHeader('Set-Cookie'.`userId=${userId}; path=/; httponly; expires=${getCookieExpires()}`)
            needSetCookie = false
          }
          res.end(JSON.stringify(userData))
        })
        return
      }

      // No route is matched, 404 is returned
      res.writeHead(404, { 'Content-Type': 'text/plain' })
      res.write('404 Not Found\n')
      res.end()
    })
}
Copy the code

Then refresh the interface and find write records in access.log

GET -- /api/blog/list? Isadmin =1 -- Mozilla/5.0 (Windows NT 10.0; Win64; X64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36 -- 1625066885837 GET -- / API /blog/list? Isadmin =1 -- Mozilla/5.0 (Windows NT 10.0; Win64; X64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36 -- 1625066886470 GET -- / API /blog/list? Isadmin =1 -- Mozilla/5.0 (Windows NT 10.0; Win64; X64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36 -- 1625066887164 GET -- / API /blog/detail? Id =17 -- Mozilla/5.0 (Windows NT 10.0; Win64; X64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36 -- 1625066917923 GET -- / API /blog/detail? Id =17 -- Mozilla/5.0 (Windows NT 10.0; Win64; X64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36 -- 1625066919531 GET -- / API /blog/list? Isadmin =1 -- Mozilla/5.0 (Windows NT 10.0; Win64; X64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36 -- 1625066920573Copy the code

Resolution of the log

Create copy. Sh under utils

#! /bin/sh
cd D:/GithubPro/node-blog/src/logs
cp access.log $(date +%Y-%m-%d).access.log
echo "" > access.log
Copy the code

After the command is executed, the current log is backed up and renamed with the timestamp. After the command is executed, the current log content is cleared