Use the nodeJs koa2 framework to develop back-end applications, and use the koa-log4 middleware to manage the access logs and system logs of nodeJs.
I. installation of koa-log4
Because the project uses koa2, the higher version of log4 is installed,
$ npm i --save koa-log4@2
If using koa1, use the directive
$ npm i --save koa-log4@1
2. Create a new log4.js file to configure log4
const path = require('path');//Introducing native path module const log4js = require('koa-log4');//Introducing koa-log4 log4js.configure({ appenders: { //Access log access: { type: 'dateFile', pattern: '-yyyy-MM-dd.log', //Generate files by date alwaysIncludePattern: true, //Filenames are always distinguished by date encoding:"utf-8", filename: path.join('logs/', 'access.log') //Build file path and file name }, //system log application: { type: 'dateFile', pattern: '-yyyy-MM-dd.log', //Generate files by date alwaysIncludePattern: true, //Filenames are always distinguished by date encoding:"utf-8", filename: path.join('logs/', 'application.log') //Build file path and file name }, out: { type: 'console' } }, categories: { default: { appenders: [ 'out' ], level: 'info' }, access: { appenders: [ 'access' ], level: 'info' }, application: { appenders: [ 'application' ], level: 'WARN'} } }); exports.accessLogger = () => log4js.koaLogger(log4js.getLogger('access')); //Log all access levels exports.logger = log4js.getLogger('application'); //Log all application levels
III. if log is used
- Access log -- record all access requests of users, and use it in the form of Middleware in the koa portal
const Koa = require('koa'); const app = new Koa(); const { accessLogger,systemLogger, } = require('./logger'); const router = new KoaRouter(); app.use(accessLogger()); //middleware
-
System log -- error recording system status
app.on('error', err => {logger.error(err); });