This is the fifth day of my participation in the August More text Challenge. For details, see:August is more challenging

This article introduces the use of log4JS, which has a great name, but has never been used. The company’s online service was down before, which caused serious concern of party A’s senior leaders. The root cause is that the log files are too large for the server partition — because the developers write a lot of logs and don’t delete them. It’s not irrelevant, but it’s a lesson. Therefore, finding a good logging system is very important in project development. This article focuses on the practice and does not say much about Log4JS.

The installation

To install using NPM, run the following command:

npm install log4js
Copy the code

Version 4.0.2 was installed for this article. Some information on the Internet does not clearly indicate the version of Log4JS, resulting in individual functions or parameters do not correspond, can not be used in the new version, therefore, in practice, must pay attention to the version of the correspondence.

A simple example

code

Log4js is relatively simple to use. Take a look at the official example:

const log4js = require('log4js'); log4js.configure({ appenders: { cheese: { type: 'file', filename: 'cheese.log' } }, categories: { default: { appenders: ['cheese'], level: 'error' } } }); const logger = log4js.getLogger('cheese'); logger.trace('Entering cheese testing'); logger.debug('Got cheese.'); Logger. The info (' Cheese is Comte. '); logger.warn('Cheese is quite smelly.'); logger.error('Cheese is too ripe! '); logger.fatal('Cheese was breeding ground for listeria.');Copy the code

Save the code version as log_test.js and run it with node. The terminal has no output. In the current directory we get the file cheese.log, which contains the following contents:

[2019-02-24T23:2400.156] [ERROR] Cheese is ripe! [2019-02-24T23:24:00.160] FATAL] Cheese was breeding ground for listeria.Copy the code

explain

The code first introduces the log4JS library and then calls log4js.configure(), defining an output source named cheese. Different output sources can set different file names, levels, and many other parameters. Note that the log level is set to Error. Only logs of error and FATAL levels are output. Use, call log4js. GetLogger (‘ cheese ‘) for instance logger, log4js provides trace, debug, info, warn, error, fatal, such as different levels of interface, can according to need to call, The author commonly used is debug, INFO, error these three functions.

Practical example

The above example is too simplistic, but here’s a little bit of a real-life example. Function: A project has different modules. Log files can be distinguished according to the module name. Logs of different modules cannot be mixed. Back up log files once a day. Can be integrated with PM2 cluster module. The output file is also output to the terminal. The code is as follows:

/* Filenames: log_utils.js /* filenames: log_utils.js When used, call getLogger to get different appenders and write to different log files. The tail -f xx. TXT command can be used to view the logs in real time. Even if the logs are backed up, it does not impact the knowledge point: Backup every day: pattern is.YYYY-MM-DD.txt every hour: Yyyy-mm-dd-mm. TXT */ const log4js = require('log4js'); log4js.configure( { appenders: { console: { type: 'console', }, datelog: { type: 'dateFile', filename: 'logs/mylog', pattern: ".yyyY-MM-dd.txt ", // alwaysIncludePattern: true, // maxLogSize: 10, // invalid // backups: 5, compress: true, daysToKeep: 2,}, datelog2: {type: 'dateFile', filename: 'logs/youlog', pattern: ".yyyy-MM-dd.txt", compress: true, daysToKeep: 2, }, // more... }, categories: { default: { appenders: ['console'], level: 'debug', }, datelog: Appenders: ['console', 'datelog'], level: 'debug', // specify the level}, datelog2: {appenders: ['console', 'datelog2'], level: 'debug', }, // more... }, // for pm2... pm2: true, disableClustering: true, // not sure... }); function getLogger(type) { return log4js.getLogger(type); } module.exports = { getLogger, }Copy the code

The code is provided as a library, using the following example:

const log4js = require('.. /lib/log_utils.js'); Const Logger = log4js.getLogger('datelog'); Logger.info ('hello world'); // Get the specified output source logger.info('hello world'); / / printCopy the code

summary

When writing, I found that it could not be output normally in the cluster mode of PM2. Later, I referred to the official information to solve the problem. Add pm2: true in the configuration function to solve the problem. There are many articles on the Web about Log4JS, but the code snippets won’t work on the new version. It is recommended to refer directly to the official example. Appenders and Categories can be cumbersome to configure if the project has too many modules and needs to distinguish between different log files, which will be looked at later.

The resources

Log4js -node. Making. IO/log4js – node…