express + log4js记录日志,包含每个请求的响应时间、请求参数和返回数据

 

log4js-node

This is a conversion of the log4js framework to work with node. I started out just stripping out the browser-specific code and tidying up some of the javascript to work better in node. It grew from there. Although it’s got a similar name to the Java library log4j, thinking that it will behave the same way will only bring you sorrow and confusion.

Changes in version 3.x

Migrating from log4js < v2.x?

There have been a few changes between log4js 1.x and 2.x (and 0.x too). You should probably read this migration guide if things aren’t working.

Features

log4js节点
这是log4js框架与node的转换。我一开始只是去掉浏览器特定的代码,整理一些javascript,以便更好地在节点中工作。它是从那里成长起来的。尽管它的名称与Java库log4j相似,但认为它的行为方式相同只会给您带来悲伤和困惑。
版本3.x中的更改
从log4js<v2.x迁移?
log4js 1.x和2.x(以及0.x)之间有一些变化。如果情况不好,您可能应该阅读此迁移指南。
特征
彩色控制台记录到stdout或stderr
文件附加器,可根据文件大小或日期配置日志滚动
SMTP附加程序
GELF附加器
日志附加程序
日志存储UDP附加程序
logFaces(UDP和HTTP)附加程序
TCP appender(当您有多个服务器但想要集中记录时很有用)
connect/express服务器的记录器
可配置日志消息布局/模式
不同日志类别的不同日志级别(将应用程序日志的某些部分设置为DEBUG,其他部分仅设置为ERRORS,等等)
内置对使用节点核心集群模块进行日志记录的支持
第三方InfluxDB附加程序

const log4js = require('log4js')


//日志对象
const logger = (name) => {
  const { logFilePath } = getValuesByNodeEnv()
  log4js.configure({
    appenders: {
      out: { type: 'console' }, //在控制台输出日志
      cheese: {
        type: 'file',
        filename: logFilePath,
        maxLogSize: 1024 * 1000 * 10 //10M
      }
    },
    categories: {
      //需要在控制台输出日志时:appenders: ['cheese', 'out']
      default: { appenders: ['cheese'], level: log4js.levels.DEBUG }
    }
  })
  return log4js.getLogger(name)
}

//添加日志
const addFormatLog = function (req, res, data) {
  const now = new Date()
  const resTime = now - req._startTime
  let resTimeLevel = '01'
  if (resTime > 5000) {
    resTimeLevel = '50'
  } else if (resTime > 2000) {
    resTimeLevel = '20'
  } else if (resTime > 1000) {
    resTimeLevel = '10'
  } else if (resTime > 500) {
    resTimeLevel = '05'
  } else if (resTime > 300) {
    resTimeLevel = '03'
  } else if (resTime > 200) {
    resTimeLevel = '02'
  } else if (resTime > 100) {
    resTimeLevel = '01'
  } else {
    resTimeLevel = '00'
  }
  const user = decodeToken({ token: req.headers.authorization })
  const {
    ip,
    headers,
    method,
    url,
    body,
    httpVersion,
    res: { statusCode, _headers }
  } = req
  let logInfo = {
    ip,
    host: headers.host,
    resTime,
    resTimeLevel,
    method,
    url,
    user,
    body,
    httpVersion,
    statusCode,
    contentLength: _headers['content-length'],
    userAgent: headers['user-agent'],
    data: data[0]
  }
  logger('log').info(`${JSON.stringify(logInfo)}`)
}

//日志中间件
const logMiddleWare = () => {
  return function (req, res, next) {
    req._startTime = new Date()

    const oldSend = res.send
    res.send = function () {
      oldSend.apply(res, arguments)
      if (typeof [...arguments][0] === 'object') {
        res.once('finish', () => addFormatLog(req, res, arguments))
      }
    }

    return next()
  }
}
  //日志
  app.use(logMiddleWare())

 https://log4js-node.github.io/log4js-node/index.html

posted @ 2022-09-21 11:43  徐同保  阅读(12)  评论(0编辑  收藏  举报  来源