node之log4js

log4js的配置文件:

"log4js": {
        "appenders": {
            "out": { "type": "console" },
            "task": { "type": "dateFile", "filename": "logs/task", "pattern": "-yyyy-MM-dd.log", "alwaysIncludePattern": true },
            "result": { "type": "dateFile", "filename": "logs/result", "pattern": "-yyyy-MM-dd.log", "alwaysIncludePattern": true },
            "error": { "type": "dateFile", "filename": "logs/error", "pattern": "-yyyy-MM-dd.log", "alwaysIncludePattern": true },
            "default": { "type": "dateFile", "filename": "logs/default", "pattern": "-yyyy-MM-dd.log", "alwaysIncludePattern": true },
            "rate": { "type": "dateFile", "filename": "logs/rate", "pattern": "-yyyy-MM-dd.log", "alwaysIncludePattern": true }
        },
        "categories": {
            "default": { "appenders": ["out", "default"], "level": "info" },
            "task": { "appenders": ["task"], "level": "info" },
            "result": { "appenders": ["result"], "level": "info" },
            "error": { "appenders": ["error"], "level": "error" },
            "rate": { "appenders": ["rate"], "level": "info" }
        }
    }

 

  当然有的项目当中用不了这么多种Log,可自行删除一些

笔者喜欢对log4js封装一下,如下:

var log4js = require('log4js');
var logger = log4js.getLogger('info');
var loggerDebug = log4js.getLogger("debug");
var loggerError = log4js.getLogger("error");
var DEFAULT_FORMAT = ':remote-addr - -' +
    ' ":method uri[:url] HTTP/:http-version"' +
    ' :status :content-length';

function init(config) {
    log4js.configure(config);
    return log4js.connectLogger(log4js.getLogger('info'), {
        level: log4js.levels.INFO,
        format: DEFAULT_FORMAT
    });
}

function info(value) {
    logger.info(value);
}

function debug(value) {
    loggerDebug.debug(value);
}

function warn(value) {
    logger.warn(value);
}

function error(value) {
    if (typeof(value) != 'object') {
        logger.error(value);
        loggerError.error(value);
    } else {
        logger.error(value.stack);
        loggerError.error(value.stack);
    }
}

module.exports = {
    init: init,
    info: info,
    debug: debug,
    warn: warn,
    error: error
}

  项目启动时首先要初始化log4js

var config = require('config');
var logger = require('./modules/logger');
logger .init(config.log4js);

logger.info('The solution is resolve');

 

 

posted @ 2017-11-02 20:49  .追风逐月  阅读(489)  评论(0编辑  收藏  举报