Node log4js log management

Node log4js log management

Entry [Log Collection]

The so-called entrance is actually the so-called collection of log information . How to collect the required information effectively and in different categories, so that we can record the first step of the log file.

log4js provides hierarchical classification and alias classification

Installation dependencies:

npm install log4js copy the code

Level

It is the grading of logs. With the grading of logs, the logs can be better displayed for us (different levels of logs are in different colors in the console, such as error is usually red). In production, you can choose to place logs, such as Avoid leaking sensitive information that belongs to .debug

The log of log4js is divided into nine levels, and the names and weights of each level are as follows:

{ ALL: new Level(Number.MIN_VALUE, "ALL" ), TRACE: new Level(5000, "TRACE" ), DEBUG: new Level(10000, "DEBUG" ), INFO: new Level(20000, "INFO" ), WARN: new Level(30000, "WARN" ), ERROR: new Level(40000, "ERROR" ), FATAL: new Level(50000, "FATAL" ), MARK: new Level(9007199254740992, "MARK" ),//2^53 OFF: new Level(Number.MAX_VALUE, "OFF" ) } Copy code

test:

Create a js file:

const log4js = require ( 'log4js' ); //logger is an instance of log4js const logger = log4js.getLogger(); logger.level = "all" logger.trace( 'this is trace' ); logger.debug( 'this is debug' ); logger.info( 'this is info' ); logger.warn( 'this is warn' ); logger.error( 'this is error' );, logger.fatal( 'this is fatal' ); logger.mark( 'this is mark' ); Copy code

Print result:

In this way, logs of different levels can be classified intuitively. On the one hand, it is convenient for us to view the terminal log, and it can also play a role in filtering afterwards.

The purpose of grading is to make it easier to find

Category

You can specify an alias when instantiating log4js, and then you can easily distinguish which file in the log

const log4js = require ( 'log4js' ); //When instantiating, the only parameter category that can be passed const logger = log4js.getLogger( 'Log 1' ); logger.level = "all" logger.trace( 'this is trace' ); logger.debug( 'this is debug' ); logger.info( 'this is info' ); logger.warn( 'this is warn' ); logger.error( 'this is error' ); logger.fatal( 'this is fatal' ); logger.mark( 'this is mark' ); Copy code

Print result:

Export [log output]

Appender

The above example is just an initialization example, output in different types and levels. The default is console output , how to save it in a file, this time you need the appender to play.

Appender provided by log4js

Both Console and File are appenders provided by log4js, in addition to:

  • DateFile: log output to a file, the log file can be rolled in a specific date mode, for example, output to default-2021-04-20.log today, and output to default-2021-04-21.log tomorrow;
  • SMTP: output log to mail;
  • Mailgun: Output logs to Mailgun through Mailgun API;
  • levelFilter can pass level filtering;
  • Wait for some other appenders, here you can see the full list.

A single Appender can serve multiple categories

  • The appender determines that the log will be written to the specified destination (stream, file, network) in a specified way
  • Category can be freely selected, combining various appenders to complete the logging function we want
  • At the same time category also defines the level of the current log classification, to finally decide whether to output the log
  • catrgory is a combination of appenders (for the version after log4js 2.0, the previous version has another configuration method)

Types and uses of Appenders (log placement)

The classification of logs can be divided into: console, stdout, dateFile, file, fileSync, stmp There are many kinds. In the new version 2.5.2, the author has added more than ten new categories of appenders. For details, please refer to this link . Here we analyze the usage of the most commonly used appenders-dateFile, file, stdout.

file

Parameter Description:

type : "file" First specify the type of appenders as file filename: used to specify the file address of the log file (ps: logs/myLog.log ) layout: select the format of log output, the default is basic maxLogSize: Maximum limit of a single file (unit: bytes) backups: the maximum number of old logs encoding: encoding format (default "utf-8") mode: default 0644, no need to configure, just use the default flags: The default "a", no configuration is required, just use the default compress: compress is true . When recording the log of the day, the old log will be compressed. The compressed file suffix is .gz (default: false ) keepFileExt: whether to keep the log file extension (the default is false , the case of the pattern, keep the default like) Copy the code
Through layout, we can customize the format of each output log. Log4js has built-in four types of formats: messagePassThrough: only output the content of the log; basic: The time, level and category of the log will be added in front of the content of the log, usually the default layout of the log; colored/coloured: add color to the log on the basis of basic. Appender Console uses this layout by default; pattern: This is a special type, you can use it to define any format you want. %r %p $m $n is the built-in inclusion specifier of log4js, which can be used to output some meta information %r log output time, formatted with toLocaleTimeString function %p log level %c log classification %h hostname of accessing computer %m Printed log subject content %n line break indicator %d log output date (formatted in ISO8601 by default) Customizable output type %d(yyyy/MM/dd-hh.mm.ss), output 2018/05/22-15.42.18 %z records the process pid number (data from the node method process.pid) %x{} outputs items in custom tokens, such as user in the above example %[The content you want to output%] is used to color the expanded content, the color is related to the log level For more details, please refer to the log4js documentation. Copy code
const log4js = require ( 'log4js' ); //Configure category and appenders log4js.configure({ replaceConsole : true , appenders : { cheese : { type : 'file' , filename : './logs/test.log' , layout : { type : "pattern" , pattern : '{"date":"%d", "level":"%p","category":"%c","host":"%h","pid":"%z","data":\'%m\'}' }, encoding : 'utf-8' , backups : 5 , compress : false , keepFileExt : true , }, }, categories : { default : { appenders : [ 'cheese' ], //set the weight level : 'debug' }, } }) let logger = log4js.getLogger(); logger.trace( 'this is trace' ); logger.debug( 'this is debug' ); logger.info( 'this is info' ); logger.warn( 'this is warn' ); logger.error( 'this is error' ); logger.fatal( 'this is fatal' ); logger.mark( 'this is mark' ); Copy code

result:

datefile

Parameter Description:

type : 'dateFile' first specify the type of appenders as dateFile filename: used to specify the file address of the log to disk (ps: ./logs/test.log ) pattern: used to specify the time interval for log splitting '.yyyy-MM' is accurate to the month'.yyyy-MM-dd' is accurate to the day'.yyyy-MM-dd-hh' accurate to the hour layout: Choose the format of the log output. In this example, pattern is used, and other types will be summarized additionally encoding: encoding format (default "utf-8") mode: default 0644, no need to configure, just use the default flags: The default "a", no configuration is required, just use the default compress: compress is true . When recording the log of the day, the old log will be compressed. The compressed file suffix is .gz (default: false ) alwaysIncludePattern: When true , the log file name will contain the previously set pattern information (default is false , but it is strongly recommended to enable it) alwaysIncludePattern is true , the log name is for example: test.log-2019-08-06 alwaysIncludePattern is false , the log name is for example: test.log daysToKeep: Specify the number of days to keep the log (default is 0, always keep) keepFileExt: Whether to keep the log file extension (default is false , if pattern is used, just keep the default) Only in alwaysIncludePattern is false effect when copy the code
const log4js = require ( 'log4js' ); //Configure category and appenders log4js.configure({ replaceConsole : true , appenders : { cheese : { //Set the type as dateFile type : 'dateFile' , //The configuration file name is test.log filename : 'logs/test.log' , //Specify the encoding format as utf-8 encoding : 'utf-8' , //Configure the layout, here use the custom pattern pattern layout : { type : "pattern" , //Configure the pattern, the following will introduce the pattern : '{"date":"%d" ,"level":"%p","category":"%c","host":"%h","pid":"%z","data":\'%m\'}' }, //Log files are cut by date (day) pattern : "-yyyy-MM-dd" , //When rolling back old log files, make sure to end with .log (only valid when alwaysIncludePattern is false) keepFileExt : true , //The output log file name always includes the pattern and the end of the date alwaysIncludePattern : true , }, }, categories : { //Set the default categories default : { appenders : [ 'cheese' ], level : 'debug' }, } }) let logger = log4js.getLogger(); logger.trace( 'this is trace' ); logger.debug( 'this is debug' ); logger.info( 'this is info' ); logger.warn( 'this is warn' ); logger.error( 'this is error' ); logger.fatal( 'this is fatal' ); logger.mark( 'this is mark' ); Copy code

After executing the above code, log4js will be divided into days, and a name will be generated every day such as

test.-2021-04-20.log
Log files.

result:

stdout

This method is used to output logs to annotated input and output streams. It is relatively simple and the configuration is as follows:

const log4js = require ( 'log4js' ); //Configure category and appenders log4js.configure({ appenders : { 'out' : { type : 'stdout' } }, categories : { default : { appenders : [ 'out' ], level : 'info' }} }); let logger = log4js.getLogger(); logger.trace( 'this is trace' ); logger.debug( 'this is debug' ); logger.info( 'this is info' ); logger.warn( 'this is warn' ); logger.error( 'this is error' ); logger.fatal( 'this is fatal' ); logger.mark( 'this is mark' ); Copy code

In this way, the console will print:

Actual combat (koa+log4js)

Configuration file: ./middlewares/logger.js

const log4js = require ( 'log4js' ) const Path = require ( 'path' ) levels = { 'trace' : log4js.levels.TRACE, 'debug' : log4js.levels.DEBUG, 'info' : log4js.levels.INFO, 'warn' : log4js.levels.WARN, 'error' : log4js.levels.ERROR, 'fatal' : log4js.levels.FATAL, } const dirName = 'info.log' const _path = Path.resolve(__dirname, `../logs/${ dirName } ` ) log4js.configure({ //The content output to the console is also output to the log file. replaceConsole : true , appenders : { cheese : { //Set the type to dateFile type : 'dateFile' , //Configure the file name filename : _path, //Specify The encoding format is utf-8 encoding : 'utf-8' , //Configure the layout, here use the custom pattern pattern //layout:'basic', //log file is cut by date (day) pattern : "yyyy-MM -dd" , //When rolling back old log files, make sure to end with .log (only valid when alwaysIncludePattern is false) keepFileExt : true , //The output log file name always includes the pattern and the end of the date alwaysIncludePattern : true , }, }, categories : { //Set the default categories default : { appenders : [ 'cheese' ], level : 'debug' }, } }) exports .logger = ( name, level ) => { const logger = log4js.getLogger(name) //The default is debug permission and above logger.level = levels[level] || levels[ 'debug' ] return logger } exports .use = ( app, level, name ) => { //Load middleware app.use(log4js.connectLogger(log4js.getLogger(name || 'logInfo' ), { level : levels[level] || levels[ 'debug' ], //Format http related information format : ':method :url :status' })); } Copy code

Use middleware in server.js

const Koa = require ( 'koa' ); const app = koa(); const log4js = require ( './middlewares/logger' ); log4js.use(app); Copy code

Use log4js

const Koa = require ( 'koa' ); const app = new Koa(); const logger = require ( './middlewares/logger' ).logger( 'server.js' , 'warn' ); logger.trace( 'This is a server page! - log4js' ); logger.debug( 'This is a server page! - log4js' ); logger.info( 'This is a server page! - log4js' ); logger.warn( 'This is a server page! - log4js' ); logger.error( 'This is a server page! - log4js' ); logger.fatal( 'This is a server page! - log4js' ); Copy code