Logging is very important for an application. Logs help developers quickly locate online problems and customize solutions. Logs contain a large amount of user information. By analyzing logs, you can obtain user behaviors, interests and preferences, and obtain user portraits, which can be used as a reference for formulating company strategies. This article will show you how to handle logging in the Node service.

First, technology selection

Three mainstream technologies were selected for comparison:

1.1 log4js

Log4js is a Node log management tool that can output customized logs to various channels. For console log output, you can render color logs, and for file log output, you can slice logs based on file size or date.

Developers familiar with Java will find Log4JS similar to log4j, a popular Java logging tool. Yes, Log4JS is a JavaScript version of Log4j and is used similarly.

1.2 winston

Winston is also a very popular Node log management tool that supports multiple transports. The default output format is JSON, or you can customize the output format. If you want to slice logs, you also need to use the winston-daily-rotate-file module.

1.3 PM2

The PM2 is a Node process management tool that provides performance monitoring, process daemon, load balancing, and log management functions. Using PM2 for log management requires only the addition of the console method call to the project and no additional code. To slice the log, use pm2-Logrotate.

Because many of the team’s internal server systems are Java-based, most of these systems use Log4J to generate logging. Log management related log collection system and log query system support log4J format logs better, so I finally choose log4JS JavaScript version of Log4j to generate logs. The basic use of Log4JS will be introduced below.

2. Basic concepts

2.1 Log Level

The default log levels of Log4JS are 9, which are listed in descending order of priority:

ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < MARK < OFF

  • When the log level is ALL, logs of ALL levels are displayed
  • When the log level is OFF, logs are disabled and no logs are generated
  • Users can also customize log levels according to their own needs

2.2 appender

An appender is used to define how and where to output. You can write logs to files, send e-mails, send data over the network, and so on. You can define multiple appenders by configuring the appenders property of an object.

Common types of appenders are:

  • Console: console output
  • File: indicates file output
  • DateFile: file output cut by date

2.3 the category

A category is a log type that specifies one or more appenders for a log type. Different log types can specify different log levels. Multiple categories can be defined by configuring the Categories attribute of an object. You must specify the default type to get the default Logger instance, and you can also get a Logger instance of the specified type by the type name.

To sum up, the appenders define where logs go, and categories classify them, with different types specifying different log levels.

Use log4js

3.1 installation

npm install log4js --save

or

yarn add log4js

3.2 Simple Use

The following example uses log4js to create the log object logger and output logs to the console and log files by calling logger.debug, logger.info, Logger.warn, logger.error, etc.

  • util/log4jsLogger.js
const path = require('path');
const log4js = require('log4js'); / / configurationlog4js
logConfigure ({appenders: {// console output console: {type: 'console'}, // log file file: {type: 'file', filename: path.join(__dirname, '.. /.. /logs/server.log'}}, categories: {// default log default: {appenders: ['file'.'console' ], level: 'debug'}}}); // Get the default log const logger =log4js.getLogger();

module.exports = logger;
Copy the code
  • server.js

The info-level log is then output by calling logger. info, the Koa used by the Web development framework.

const Koa = require('koa');
const router = require('./router');
const logger = require('./util/log4jsLogger');

const port = 3000;
const app = new Koa()
    .use(router.routes())
    .use(router.allowedMethods());

app.listen(port, () => {
    logger.info(`Server running on port ${port}`);
});
Copy the code

3.3 Log Format

Log4js sets the log format with layouts. Built-in layouts include:

  • Basic contains the basic log format of timestamp, log level, and log type
  • The colored format is the same as basic, except that different log levels display different colors
  • Dummy displays only the content of the first parameter. No timestamp, log level, or log type information is displayed
  • Pattern allows you to customize the layout of the format

Example:

Default log format:

[2020-04-01T11:33:43.317] [INFO] Default-server running on port 3000Copy the code

Custom log format:

2020-04-01 11:33:43.317 [INFO] Server running on port 3000
Copy the code

Code:

// Custom log format const layout = {type: 'pattern',
    pattern: '%d{yyyy-MM-dd hh:mm:ss.SSS} [%p] %m'
};

logConfigure ({appenders: {// console output console: {type: 'console'}, // Log file, set the log format file: {type: 'file', filename: path.join(__dirname, '.. /.. /logs/server.log'), layout}}, Categories: {// Default log default: {appenders: ['file'.'console' ], level: 'debug'}}});Copy the code

3.4 Log Cutting

If all logs are output to a file, the log file becomes larger, which makes it inconvenient to back up and view logs. The appender can be sliced by date by specifying type dateFile.

// Log configurationlogConfigure ({appenders: {// console output console: {type: 'console'}, // log file file: {type: 'dateFile',
            filename: path.join(__dirname, '.. /.. /logs/server.log'), // Log file name suffix pattern:'.yyyy-MM-dd'}}, categories: {// Default log default: {appenders: ['file'.'console' ], level: 'debug'}}});Copy the code

If the service is deployed on April 1, the log will be output to the service.log file. On April 2, the service. Log will be renamed to server.log.2020-04-01.

3.5 Output Multiple Files

In addition to the full log output to server.log, the following example also outputs error and higher logs to server-error.log.

  • util/log4jsLogger.js
const path = require('path');
const log4js = require('log4js'); / / configurationlog4js
logConfigure ({appenders: {// console output console: {type: 'console'}, // all log files allFile: {type: 'file', filename: path.join(__dirname, '.. /.. /logs/server.log'}, // error log file errorFile: {type: 'file', filename: path.join(__dirname, '.. /.. /logs/server-error.log'}}, categories: {// Default log, output debug and higher logs default: {appenders: ['allFile'.'console' ], level: 'debug'Error: {appenders: [appenders: ['errorFile' ], level: 'error'}}}); // Get the default log const defaultLogger =log4js.getLogger(); // Get error level logs const errorLogger =log4js.getLogger('error'); Const loggerProxy = {}; // Log proxy calls default log and 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

3.6 cover the console

Logger. debug, Logger. info, Logger. warn, logger.error and other methods need to be called to use log4JS. You can use log4JS to output logs by overriding console.

/** * Create log proxy method * @paramlogLevel Log Level * @param Logger log object * @return {function} * /function createLogProxy (logLevel, logger) {
    return(... param) => { logger[logLevel](... param); }; } console.log = createLogProxy('debug', logger);
console.info = createLogProxy('info', logger);
console.warn = createLogProxy('warn', logger);
console.error = createLogProxy('error', logger);
Copy the code

To ensure that all logs are exported to log files, get the Logger object and override the console method as early as possible.

Four,

This chapter describes how to use log4JS and provides examples of common functions. For more functions of Log4JS, see log4js-node.github. IO /log4js-node…