Nodejs log4js v6.1 快速集成

Nodejs log4js v6.1 快速集成

log4js 是 nodejs 出色的日志处理框架之一, 本文将帮助你快速集成到你的应用

安装

npm install --save log4js@6.1.0
// or
npm i -S log4js

log4js 配置

注: 此配置基于log4js v6.1.0

// file: logger.json
{
  "appenders": {
    "out": {
      "type": "console"
    },
    "default": {
      "type": "dateFile",
      "filename": "logs/default.log",
      "pattern": "yyyy-MM-dd",
      "compress": true,
      "alwaysIncludePattern": true,
      "daysToKeep": 15,
      "keepFileExt": true
    },
    "error": {
      "type": "dateFile",
      "filename": "logs/error.log",
      "pattern": "yyyy-MM-dd",
      "compress": true,
      "alwaysIncludePattern": true,
      "daysToKeep": 15,
      "keepFileExt": true
    },
    "maxInfo": {
      "type": "logLevelFilter",
      "appender": "default",
      "level": "debug",
      "maxLevel": "info"
    },
    "minError": {
      "type": "logLevelFilter",
      "appender": "error",
      "level": "error"
    }
  },
  "categories": {
    "default": {
      "appenders": [
        "out",
        "maxInfo",
        "minError"
      ],
      "level": "all",
      "enableCallStack": true
    }
  },
  "replaceConsole": true
}

加载配置

// file: app.js
const log4js = require('log4js');
const config = require('./logger.json');

log4js.configure(config);
const logger = log4js.getLogger('custom-category');

logger.info('info');
logger.debug('debug');
logger.warn('warn');
logger.error('error');