The introduction

Functions of logs:

(1) Cleared interface for recording user requests

(2) Whether any error occurs when requesting the interface

(3) Error log, easy to repair errors in time

(4) It is convenient to reproduce errors and debug, etc

Here we use log4JS for log processing

Log4js configuration

1. Install log4JS

npm install log4js --save
Copy the code

Create config/ logconfig.js

const express = require('express')
const log4js = require('log4js') // Load the log4js module
const path = require('path')
const app = express()

log4js.configure({
  appenders: {
    // Console output
    console: { type: 'console' },
    // All log files
    app: { 
      type: 'file'.filename: path.join(__dirname, '.. /logs/app'),
      maxLogSize: 1024 * 500.// The size of a file is exceeded, and a new file is automatically generated
      backups: 2.// The number of backup files
      pattern: "_yyyy-MM-dd.log".alwaysIncludePattern: true,},// Error log file
    errorFile: { 
      type: 'file'.filename: path.join(__dirname, '.. /logs/error'),
      maxLogSize: 1024 * 500.// The size of a file is exceeded, and a new file is automatically generated
      backups: 2.// The number of backup files
      pattern: "_yyyy-MM-dd.log".alwaysIncludePattern: true,}},categories: {
    // Default log. Logs of debug or higher levels are generated
    default: { appenders: [ 
      'app'.'console' // Do not output to the console].level: 'debug' },
    // Error logs are generated at the error level or higher
    error: { appenders: [ 'errorFile'].level: 'error'}},replaceConsole: true./ / replace the console log
});

// Get the default log
const defaultLogger = log4js.getLogger()
// Get the error level log
const errorLogger = log4js.getLogger('error')

// The log proxy calls both the default log and the error log
const loggerProxy = {};
const levels = log4js.levels.levels;
levels.forEach(level= > {
    const curLevel = level.levelStr.toLowerCase();
    loggerProxy[curLevel] = (. params) = >{ defaultLogger[curLevel](... params); errorLogger[curLevel](... params); }});module.exports = loggerProxy
Copy the code

The configuration file comments here are pretty clear, so I won’t explain them too much, but I’ll replace them with console.log in our project

The root directory of the project has generated logs directory, and there are two log files, open look, the log is very clear, when the request, request parameters are what

The/API /user/info interface needs to pass in an ID. If the id is empty, the utils.senderror () method will be invoked

if(! params.id){ utils.sendError(res,'User ID cannot be null')
  return
}
Copy the code

The sendError method in utils.js is implemented as follows:

sendError(res, message, code = 500){
  logger.error(typeof message, message)
  if(typeof message === 'string') {return res.status(500).send({
      code: code,
      message: message
    })
  }

  if(typeof message === 'object') {return res.status(500).send(message)
  }
}
Copy the code

An error is logged, and the interface returns 500 errors or custom error codes, and an error message

conclusion

Logging is an essential part of our daily development projects, both in development and production environments, so you can apply it to your own projects.

Front end play Back End