3.0.5版本的log4.js记录不同的日志,按小时划分

写配置(log_config.js)

let log4js = require('log4js');
let path = require('path');
let fs = require('fs');

let basePath = path.join(__dirname, '/logs/');
let defaultPath = path.join(basePath, '/default_database/');
let writeDbPath = path.join(basePath, '/write_database/');
let readDbPath = path.join(basePath, '/read_database/');

let confirmPath = function (pathStr) {
    console.log("pathStr",pathStr);
    if (!fs.existsSync(pathStr)) {
        fs.mkdirSync(pathStr);
        console.log('createPath: ' + pathStr);
    }
};
//创建log的根目录'logs'
if (basePath) {
    confirmPath(basePath);
    //根据不同的logType创建不同的文件目录
    confirmPath(defaultPath);
    confirmPath(writeDbPath);
    confirmPath(readDbPath);
}

log4js.configure({
    appenders: {
        out: {type: 'console'},
        default: {
            type: 'dateFile',
            filename: defaultPath,
            "pattern": "yyyy-MM-dd-hh.log",
            alwaysIncludePattern: true
        },
        write_db: {
            type: 'dateFile',
            filename: writeDbPath,
            "pattern": "yyyy-MM-dd-hh.log",
            alwaysIncludePattern: true
        },
        read_db: {
            type: 'dateFile',
            filename: readDbPath,
            "pattern": "yyyy-MM-dd-hh.log",
            alwaysIncludePattern: true
        }
    },
    categories: {
        default: {
            appenders: ['default'],
            level: 'info'
        },
        write_db: {
            appenders: ['write_db'],
            level: 'info'
        },
        read_db: {
            appenders: ['read_db'],
            level: 'info'
        }
    },
    replaceConsole: true              //是否替换console.log
});


module.exports = log4js;

写应用(index.js)

let log4js = require('./log_config');

let defaultLog = log4js.getLogger('default') ;        //此处使用category的值
let writeLog = log4js.getLogger('write_db') ;        //此处使用category的值
let readLog = log4js.getLogger('read_db')    ;      //此处使用category的值

defaultLog.info("default");
writeLog.info("000");
readLog.info("111");

这是实现的代码

~~~~

未经允许不得转载:朱邦邦的博客 » 3.0.5版本的log4.js记录不同的日志,按小时划分

赞 (1)

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址