欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

nodelog4js配置解析

程序员文章站 2022-03-30 11:53:56
1.新建log4js.js const log4js = require('log4js'); log4js.configure({ "re...

1.新建log4js.js

const log4js = require('log4js');
log4js.configure({
  "replaceconsole": true,
  "appenders": {
    "stdout": {//控制台输出
      "type": "console"
    },
    "req": {
      "type": "datefile",
      "filename": "logs/reqlog/",
      "pattern": "req-yyyy-mm-dd.log",
      "alwaysincludepattern": true,
      "maxlogsize": 104800,
      "backups": 100
    },
    "err": {//错误日志
      "type": "datefile",
      "filename": "logs/errlog/",
      "pattern": "err-yyyy-mm-dd.log",
      "alwaysincludepattern": true,
      "maxlogsize": 104800,
      "backups": 100
    },
    "oth": {//其他日志
      "type": "datefile",
      "filename": "logs/othlog/",
      "pattern": "oth-yyyy-mm-dd.log",
      "alwaysincludepattern": true,
      "maxlogsize": 104800,
      "backups": 100
    }
  },
  "categories": {//level:设置级别
    "default": {
      "appenders": [
        "stdout",
        "req"
      ],
      "level": "debug"
    },
    "err": {
      "appenders": [
        "stdout",
        "err"
      ],
      "level": "error"
    },
    "oth": {
      "appenders": [
        "stdout",
        "oth"
      ],
      "level": "info"
    }
  }
});
exports.getlogger = function (name) {//name取categories项
    return log4js.getlogger(name || 'default')
};

exports.uselogger = function (app, logger) {//用来与express结合
    app.use(log4js.connectlogger(logger || log4js.getlogger('default'), {
        format: '[:remote-addr :method :url :status :response-timems][:referrer http/:http-version :user-agent]'//自定义输出格式
    }))
};

1.引入log4js文件

const log4js= require('./logs.js')
const logger = log4js.getlogger()//根据需要获取logger
const errlogger = log4js.getlogger('err')
const othlogger = log4js.getlogger('oth')
log4js.uselogger(app,logger)
log4js.uselogger(app,errlogger)
log4js.uselogger(app,othlogger)