Node.js series of articles: use console to output log files

Usually when we write Node.js programs, we are used to using console.log to print log information, but this is limited to console output. Sometimes we need to output information to log files. In fact, console can also be used to achieve this purpose. Yes, let me briefly introduce it today.

We first create the following files:

// index.js

let fs = require('fs');

let options = {
    flags: 'a',         // append模式
    encoding: 'utf8',   // utf8编码
};

let stdout = fs.createWriteStream('./stdout.log', options);
let stderr = fs.createWriteStream('./stderr.log', options);

// 创建logger
let logger = new console.Console(stdout, stderr);

for (let i = 0; i < 100; i++) {
    logger.log(`log message ${i}`);
    logger.error(`err message ${i}`);
}

In the above code, we actually created an instance of the console.Console class. This class needs to specify two parameters, namely the standard output stream and the standard error output stream. Under normal circumstances, it actually corresponds to process.stdout and process. .stderr, in the above code, we changed the two output streams to file output streams and specified them as file append mode, so that the log information can be output to the specified file. Running the above code will generate two files, stdout.log and stderr.log.

The contents of the stdout.log file are as follows:

log message 0
log message 1
log message 2
log message 3
log message 4
log message 5
log message 6
log message 7
log message 8
log message 9
log message 10
...

The contents of the stderr.log file are as follows:

err message 0
err message 1
err message 2
err message 3
err message 4
err message 5
err message 6
err message 7
err message 8
err message 9
err message 10
...

It seems that the information is relatively simple. It does not look like a log file. We may have to add a time to each log. Let's first add a format prototype method to the Date object:

// 添加format方法
Date.prototype.format = function (format) {

    if (!format) {
        format = 'yyyy-MM-dd HH:mm:ss';
    }
    
    // 用0补齐指定位数
    let padNum = function (value, digits) {
        return Array(digits - value.toString().length + 1).join('0') + value;
    };

    // 指定格式字符
    let cfg = {
        yyyy: this.getFullYear(),                          // 年
        MM: padNum(this.getMonth() + 1, 2),                // 月
        dd: padNum(this.getDate(), 2),                     // 日
        HH: padNum(this.getHours(), 2),                    // 时
        mm: padNum(this.getMinutes(), 2),                  // 分
        ss: padNum(this.getSeconds(), 2),                  // 秒
        fff: padNum(this.getMilliseconds(), 3),            // 毫秒
    };

    return format.replace(/([a-z]|[A-Z])(\1)*/ig, function (m) {
        return cfg[m];
    });
}

Then rewrite the previous main file:

// index.js

let fs = require('fs');

let options = {
    flags: 'a',         // append模式
    encoding: 'utf8',   // utf8编码
};

let stdout = fs.createWriteStream('./stdout.log', options);
let stderr = fs.createWriteStream('./stderr.log', options);

// 创建logger
let logger = new console.Console(stdout, stderr);

// 添加format方法
Date.prototype.format = function (format) {

    if (!format) {
        format = 'yyyy-MM-dd HH:mm:ss';
    }
    
    // 用0补齐指定位数
    let padNum = function (value, digits) {
        return Array(digits - value.toString().length + 1).join('0') + value;
    };

    // 指定格式字符
    let cfg = {
        yyyy: this.getFullYear(),                          // 年
        MM: padNum(this.getMonth() + 1, 2),                // 月
        dd: padNum(this.getDate(), 2),                     // 日
        HH: padNum(this.getHours(), 2),                    // 时
        mm: padNum(this.getMinutes(), 2),                  // 分
        ss: padNum(this.getSeconds(), 2),                  // 秒
        fff: padNum(this.getMilliseconds(), 3),            // 毫秒
    };

    return format.replace(/([a-z]|[A-Z])(\1)*/ig, function (m) {
        return cfg[m];
    });
}

for (let i = 0; i < 100; i++) {

    let time = new Date().format('yyyy-MM-dd HH:mm:ss.fff');

    logger.log(`[${time}] - log message ${i}`);
    logger.error(`[${time}] - err message ${i}`);
}

Rerun the program and review the contents of both log files.

The contents of stdout.log are as follows:

[2018-04-27 07:30:54.309] - log message 0
[2018-04-27 07:30:54.312] - log message 1
[2018-04-27 07:30:54.312] - log message 2
[2018-04-27 07:30:54.312] - log message 3
[2018-04-27 07:30:54.312] - log message 4
[2018-04-27 07:30:54.312] - log message 5
[2018-04-27 07:30:54.312] - log message 6
[2018-04-27 07:30:54.312] - log message 7
[2018-04-27 07:30:54.312] - log message 8
[2018-04-27 07:30:54.312] - log message 9
[2018-04-27 07:30:54.312] - log message 10
...

The contents of stderr.log are as follows:

[2018-04-27 07:30:54.309] - err message 0
[2018-04-27 07:30:54.312] - err message 1
[2018-04-27 07:30:54.312] - err message 2
[2018-04-27 07:30:54.312] - err message 3
[2018-04-27 07:30:54.312] - err message 4
[2018-04-27 07:30:54.312] - err message 5
[2018-04-27 07:30:54.312] - err message 6
[2018-04-27 07:30:54.312] - err message 7
[2018-04-27 07:30:54.312] - err message 8
[2018-04-27 07:30:54.312] - err message 9
[2018-04-27 07:30:54.312] - err message 10
...

Such a simple log output is done.

References:

https://nodejs.org/api/console.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324917514&siteId=291194637