preface

When the project goes online, it still meets the situation that does not meet the expectation. In this case, a proper record is very important (at the same time, a system without a log recording link should never be put into production).

Log4js-node log4JS-Node log4JS-Node log4JS-Node log4JS-Node log4JS-Node log4JS-Node log4JS-Node log4JS-Node

Of course, they are all very powerful:

  • Color console records to STDout or STderr
  • File add-on that configures log scrolling based on file size or date
  • Logger for connector/fast server
  • Configurable log message layout/mode
  • Different log levels for different log categories (set some parts of the application log to DEBUG, others to ERRORS only, etc.)

Not only that, it also has:

  • SMTP
  • GELF
  • Loggly
  • Logstash (UDP and HTTP)
  • logFaces (UDP and HTTP)
  • RabbitMQ
  • Redis
  • Hipchat
  • Slack
  • mailgun
  • InfluxDB

Design ideas

In a way, log4JS is out of the box, we just need to configure it, so there’s a layer of encapsulation here

Start with the configuration file (it is recommended to consult the Github documentation or the source code to understand the configuration)

Source configuration file description TS

export interface Configuration {
  appenders: { [name: string]: Appender; };
  categories: { [name: string] : {appenders: string[]; level: string; enableCallStack? :boolean; } };
  pm2?: boolean; pm2InstanceVar? :string; levels? : Levels; disableClustering? :boolean;
}
Copy the code

coding

Implementation configuration file (here log files are used to fetch records)

 /** * log4j */
    log4j: {

        / / the log4j configuration items
        configuration: {
            //
            replaceConsole: true./ / open pm2
            pm2: true.appenders: {
                // Console output
                stdout: {
                    type: 'console'
                },

                trace: {
                    type: 'dateFile'.filename: '.. /logs/app/trace/'.pattern: 'yyyy-MM-dd.log'.// Maximum storage space for each log
                    // maxLogSize: 10,
                    // Include the model
                    alwaysIncludePattern: true
                },

                debug: {
                    type: 'dateFile'.filename: '.. /logs/app/debug/'.pattern: 'yyyy-MM-dd.log'.// maxLogSize: 10,
                    alwaysIncludePattern: true
                },
                info: {
                    type: 'dateFile'.filename: '.. /logs/app/info/'.pattern: 'yyyy-MM-dd.log'.// maxLogSize: 10,
                    alwaysIncludePattern: true
                },
                warn: {
                    type: 'dateFile'.filename: '.. /logs/app/warn/'.pattern: 'yyyy-MM-dd.log'.// maxLogSize: 10,
                    alwaysIncludePattern: true
                },
                error: {
                    type: 'dateFile'.filename: '.. /logs/app/error/'.pattern: 'yyyy-MM-dd.log'.// maxLogSize: 10,
                    alwaysIncludePattern: true
                },
                fatal: {
                    type: 'dateFile'.filename: '.. /logs/app/fatal/'.pattern: 'yyyy-MM-dd.log'.// maxLogSize: 10,
                    alwaysIncludePattern: true}},categories: {
                Appenders: indicates the appender. Take appenders as the appenders item. Level: indicates the set level
                trace: {appenders: ['stdout'.'trace'].level: 'trace'},
                debug: { appenders: ['stdout'.'debug'].level: 'debug' },
                default: {appenders: ['stdout'.'info'].level: 'info'},
                warn: {appenders: ['stdout'.'warn'].level: 'warn'},
                error: {appenders: ['stdout'.'error'].level: 'error'},
                fatal: {appenders: ['stdout'.'fatal'].level: 'fatal'}}},// Log output level
        levels: ['INFO'.'WARN'.'DEBUG'].// Customize formatted output items
        format: '[:remote-addr :method :url :status :response-time ms][:referrer HTTP/:http-version :user-agent]'
    }
Copy the code

Then wrap the LoggerFactory

const log4js = require('log4js');

/ * * *@author yichengxianCategories * const logger = loggerFactory.getLogger ('info'); loggerFactory.getLogger ('info'); * * logger.debug('%s','debug log '); * logger.info('%s','info log '); * logger.error('%s','error log '); */ / All the above will be put into the info Categories file * */
class LoggerFactory {

    /** * Configure log4j *@param configuration {Configuration}
     */
    static configure(configuration) {

        log4js.configure(configuration)
    }

    /**
     * app use this
     * @param app 
     * @param Name refer to getLogger *@param Format Format output without asterisk (*/)
    static useLogger(app, name, format) {
        let options = {};
        if (undefined! == format) { options.format = format; } app.use(log4js.connectLogger(this.getLogger(name),options));
    }

    / * * *@param Name Do not set categories to the default info *@return {Logger}* /
    static getLogger(name) {
        const logger = log4js.getLogger(name || 'info');
        returnlogger; }}module.exports = LoggerFactory

Copy the code

Configuring the use of Express:

# to load the configuration file loggerFactory. Configure (config. Log4j. Configuration); # Use Express app (middleware logic) loggerFactory.uselogger (app)Copy the code

conclusion

The good use of logging allows users to quickly locate anomalies and their specific locations, which can solve urgent problems.

Water ah, log4JS design is lifelike, simple and practical, simple record

github.com/yichengxian…