Logger.js 2.46 KB
/**
 * 重写日志生成
 * @type {exports}
 */
var winston = require('winston');
var _ = require('lodash');
var mkdirp = require('mkdirp');
var _path = require('path');

/**
 * 日志配置
 * @type {Object}
 */
var logConfig = {};
var log = function (name) {
    var flag = false;
    if (name == 'error') {
        flag = true;
    }
    logConfig = {
        file: name + '.log',
        level: name,
        trans: {
            Console: {
                handleExceptions: flag,
                colorize: 'all',
                prettyPrint: true
            },
            File: {
                filename: "",
                maxsize: 50 * 1024 * 1024,
                handleExceptions: flag
            },
            exitOnError: false
        }
    };
    return logConfig;
};
/**
 * 配置日志
 * @param  {String}  path      路径
 * @param  {String}  level     日志级别
 * @param  {Object}  transConfig     配置项
 * @return {Object}            日志
 */
function configLogger(path, level, transConfig) {
    var trans = [], config = {}, consoleOpt, fileOpt;
    //配置输出控制台的日志
    if (transConfig && transConfig.Console) {
        consoleOpt = transConfig.Console;
        trans.push(new (winston.transports.Console)(consoleOpt));
    }
    //配置写文件的日志
    if (path) {
        transConfig.File.filename = path;
        fileOpt = transConfig.File;
        trans.push(new (winston.transports.File)(fileOpt));
    }
    //退出错误配置,进行设置
    config.exitOnError = transConfig.exitOnError;
    //等级
    config.level = level;
    config.transports = trans;
    //根据配置参数,实例化Winston
    var logger = new (winston.Logger)(config);
    return logger;
}
/**
 * 生成文件路径
 * @param  {String} logsConfig 文件路径
 * @return {Object}      一组日志配置
 */
function init(logsConfig) {
    //创建日志目录,路径不存在
    var path = logsConfig.src;
    if (!path) {
        console.error('path can not be null!');
    }
    //创建目录
    try {
        mkdirp.sync(path);
    } catch (err) {
        console.error(err);
        path = false;
    }
    var loggers = {};
    var config = {};
    _.forEach(logsConfig.consoles, function (v, k) {
        config[v] = log(v);
    });
    _.forEach(config, function (v, k) {
        var pathfile = path ? _path.join(path, v.file) : false;
        loggers[k] = configLogger(pathfile, v.level, v.trans);
    });
    return loggers;
}
module.exports = init;