Entry [Log Collection]

The so-called entry, in fact, is the so-called log information collection, how to effectively and categorically collect the required information, so that we record the log file first step.

Log4js provides hierarchical and alias categories

Install dependencies:

npm install log4js
Copy the code

Level (Level)

It is the classification of logs, which can better display logs for us (different levels of logs are in different colors in the console, for example, error is usually red). You can selectively produce logs, for example, to prevent sensitive information belonging to. Debug from being leaked

Log4js logs are divided into nine levels. Each level has the following names and weights:

{
  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 the code

Testing:

Create 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 the code

Print result:

This makes it easy to categorize different levels of logs. On the one hand, it is convenient for us to view terminal logs, and it can also play a role in filtering later.

The purpose of grading is to make it easy to find

Type (category)

You can specify an alias when you instantiate log4JS, and then you can easily distinguish which file is in the log

const log4js = require('log4js');

// The only category parameter that can be passed when instantiated
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 the code

Print result:

Exit [Log Output]

Appender

The above example is just an initialization instance, with different types and levels of output. The default is console output and how to save it in a file. This is where appender comes in.

Log4js Appender

Console and File are log4JS appenders.

  • DateFile: Logs are output to a file. The log file can be rolled in a specified date mode. For example, the log file is output to default-2021-04-20.log today and default-2021-04-21.log tomorrow.
  • SMTP: outputs logs to emails.
  • Mailgun: Logs are output to Mailgun through the Mailgun API.
  • LevelFilter can be filtered by level.
  • And other appenders, you can see the full list here.

A single Appender can serve multiple categories

  • Appender determines that logs will be written to the specified destination (stream, file, network) in the specified way
  • Categories are free to choose and compose various appenders to do the logging we want
  • The category also defines the level of the current log category to determine whether to output the log
  • Catrgory is a combination of appenders (for versions after Log4JS 2.0, previous versions have a different configuration)

Type and Use of Appenders (Log drop disk)

Logs can be classified into console, STDout, dateFile, file, fileSync, STMP… Appenders: dateFile, file, stdout, dateFile, dateFile, stdout

file

Parameter Description:

typeFilename: specifies the address of the file (ps: "logs/ mylog.log") in which the log is dropped. Default: Basic maxLogSize: Maximum limit on a single file backups: Maximum number of old logs Encoding: Encoding format (default: UTF-8) mode: Maximum number of old logs Backups: Maximum number of old logs Default 0644 Flags: the default value is a. Compress: compress istrue, the system compresses logs of the current day. Gz (Default:falseKeepFileExt: indicates whether to keep the log file extension. The default value is keepFileExtfalseIn the case of Pattern, keep the default.Copy the code
You can customize the format of each output log by using Layout. Log4js has four built-in formats: messagePassThrough: outputs only the log content; Basic: Add time, log level, and log type in front of the log content. Colored/Coloured: Coloured logs based on basic. This layout is used by appender Console by default. Pattern: This is a special type that can be used to define any format you want. %r %p$m $n%r log output time %r log output time %r log output time Format the toLocaleTimeString function %p Log level % C Log classification %h Hostname for accessing the computer %m Log subject content printed %n newline identifier %d Log output date (formatted in ISO8601 mode by default) %x{} Add tokens %d{yyyy/MM/ DD-hh.mm Items, such as user %[desired output %] in the above example, are used to color the expanded content. For more details on colors and log levels, see the log4js documentation.Copy the 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 the code

Results:

datefile

Parameter Description:

type : 'dateFile'Set the appenders type to dateFile filename: specifies the file address of the log falling disk (ps: "./logs/test.log "). Pattern: specifies the interval for log splitting'.yyyy-MM'Accurate to month'.yyyy-MM-dd'Accurate to the day'.yyyy-MM-dd-hh'Layout: specifies the log output format. In this example, pattern is used. Other types will be added. The default value is a. compress: compress istrue, the system compresses logs of the current day. Gz (Default:false) alwaysIncludePattern: whentrueWhen,logThe file name will contain the previously set pattern information (default isfalseAlwaysIncludePattern is highly recommendedtrueLog name, for example, test.log-2019-08-06 alwaysIncludePattern isfalseLog daysToKeep: specifies the number of days that logs are kept. (The default value is 0 and logs are kept all the time.) keepFileExt: specifies whether to keep the log file name extensionfalseIn the case of pattern, keep the default) only if alwaysIncludePattern isfalseEffective whenCopy the code
const log4js = require('log4js');
// Configure category and appenders
log4js.configure({
    replaceConsole: true.appenders: {
        cheese: {
            // Set type to dateFile
            type: 'dateFile'.// The configuration file name is test.log
            filename: 'logs/test.log'.// Set the encoding format to UTF-8
            encoding: 'utf-8'.// Configure layout, where custom pattern is used
            layout: {
                type: "pattern".// Configuration mode, described below
                pattern: '{"date":"%d","level":"%p","category":"%c","host":"%h","pid":"%z","data":\'%m\'}'
            },
            // Log files are cut by date (day)
            pattern: "-yyyy-MM-dd".// Roll back old log files with.log endings (only valid if alwaysIncludePattern is false)
            keepFileExt: true.// The output log file names always contain the pattern date ending
            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 the code

After the above code is executed, log4JS will be divided into days and generate a log file named test.-2021-04-20.log every day.

Results:

stdout

This method is used to output logs to the annotation input/output stream. 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 the code

In this case, 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 output to the console is also output to the log file
    replaceConsole: true.appenders: {
        cheese: {
            // Set type to dateFile
            type: 'dateFile'.// The configuration file name
            filename: _path,
            // Set the encoding format to UTF-8
            encoding: 'utf-8'.// Configure layout, where custom pattern is used
            // layout: 'basic',
            // Log files are cut by date (day)
            pattern: "yyyy-MM-dd".// Roll back old log files with.log endings (only valid if alwaysIncludePattern is false)
            keepFileExt: true.// The output log file names always contain the pattern date ending
            alwaysIncludePattern: true,}},categories: {
        // Set the default categories
        default: {appenders: ['cheese'].level: 'debug'}}})exports.logger = (name, level) = > {
    const logger = log4js.getLogger(name)
    // The default permission is DEBUG or higher
    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 information
        format: ':method :url :status'
    }));
}
Copy the code

Middleware is used in server.js

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

Using 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 the code