使用Winston覆盖console.log |错误不再起作用

时间:2019-05-12 08:48:41

标签: javascript node.js console.log winston

一段时间以来,我们使用一个简单的lib来覆盖默认的console.log |。 Winston错误,但不再起作用。

这是我们的小模块:

const path = require('path')
const fs = require('fs-extra')
const { createLogger, format, transports } = require('winston')
const { combine, timestamp, label, printf, colorize } = format
const packageJsonPath = path.join(process.cwd(), 'package.json')
const packageObj = fs.readJsonSync(packageJsonPath)
const name = packageObj.name || 'app'

// Custom format of the logs
const myFormat = printf(info => {
  let indent
  if (process.env.ENVIRONMENT && process.env.ENVIRONMENT !== 'production') {
    indent = 2
  }
  const message = JSON.stringify(info.message, false, indent)
  return `[${info.label}] ${info.timestamp} ${info.level}: ${message}`
})

// Custom logging handler
const logger = createLogger({
  format: combine(colorize(), label({ label: name }), timestamp(), myFormat),
  transports: [new transports.Console()],
})

// Override the base console log with winston
console.log = logger.info
console.warn = logger.warn
console.error = logger.error

但是抛出的错误是:

1|ms-item  | TypeError: self._addDefaultMeta is not a function
1|ms-item  |     at Console.DerivedLogger.(anonymous function) [as log] (/home/carmichael/code/g2/backend/ms_item/node_modules/winston/lib/winston/create-logger.js:80:14)
1|ms-item  |     at Server._src_app__WEBPACK_IMPORTED_MODULE_2__.default.listen (webpack-internal:///./server.js:14:11)
1|ms-item  |     at Object.onceWrapper (events.js:277:13)
1|ms-item  |     at Server.emit (events.js:189:13)
1|ms-item  |     at Server.<anonymous> (/usr/lib/node_modules/pm2/node_modules/@pm2/io/build/main/metrics/httpMetrics.js:147:37)
1|ms-item  |     at emitListeningNT (net.js:1304:10)
1|ms-item  |     at process._tickCallback (internal/process/next_tick.js:63:19)
1|ms-item  |     at Function.Module.runMain (internal/modules/cjs/loader.js:757:11)
1|ms-item  |     at startup (internal/bootstrap/node.js:283:19)
1|ms-item  |     at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

还有其他人遇到相同的问题并找到解决方案吗?

2 个答案:

答案 0 :(得分:4)

这是使用ES6 +语法编写的最佳解决方案:

console.log = (...args) => logger.info.call(logger, ...args);
console.info = (...args) => logger.info.call(logger, ...args);
console.warn = (...args) => logger.warn.call(logger, ...args);
console.error = (...args) => logger.error.call(logger, ...args);
console.debug = (...args) => logger.debug.call(logger, ...args);

答案 1 :(得分:0)

好吧,我想我从Winston的apply函数中找到了一个稳定的解决方案:

// Override the base console log with winston
console.log = function(){
  return logger.info.apply(logger, arguments)
}
console.error = function(){
  return logger.error.apply(logger, arguments)
}
console.info = function(){
  return logger.warn.apply(logger, arguments)
}