简体   繁体   English

将消息记录为快速app.listen回调

[英]Log message as express app.listen callback

I am introducing winston logging into my application and i would like to replace all info or error level logs with winston's .info and .error . 我正在向应用程序中引入Winston日志记录,我想用winston的.info.error替换所有信息或错误级别的日志。 So far everything works except when I try and log a info message from within app.listen callback. 到目前为止,一切正常,除非我尝试从app.listen回调中记录信息消息。

appStartup.js file where logger is defined 定义记录器的appStartup.js文件

const app = require('express')();
const co = require('co');
const cors = require('cors');
const winston = require('winston');

const loggerTimeFormat = () => (new Date()).toLocaleTimeString();

const winstonLogger = new winston.Logger({
  transports: [
    new winston.transports.Console({
      timestamp: loggerTimeFormat,
    }),
  ],
});

module.exports = function appStartup() {
  co(function* services() {
    app.db = mongo.connect();
    app.use(cors());
    app.set('logger', winstonLogger);
  }).catch((e) => {
    console.error(e);
  });

  return app;
};

In my server.js file I have: 在我的server.js文件中,我有:

const app = require('./src/appStartup');

const appPort = process.env.PORT;
app().listen(appPort, () => {
  console.log('Info message here');
});

I would like to replace the console.log in server.js with a winston info log I tried doing this: 我想用我尝试执行的winston info日志替换server.jsconsole.log

const app = require('./src/appStartup');
const appPort = process.env.PORT;
const appObj = app();

appObj.listen(appPort, (appObj.get('logger')) => {
  logger.info('Info message here');
});

Not sure if that's the right syntax though, I get Parsing error: Assigned to rvalue for appObj in appObj.get('logger') . 虽然不确定这是否是正确的语法,但我收到Parsing error: Assigned to rvalueappObj.get('logger')appObj Parsing error: Assigned to rvalue Any idea how can I make this work? 你知道我该怎么做吗?

Don't you mean this? 你不是这个意思吗

appObj.listen(appPort, (logger = appObj.get('logger')) => {
  logger.info('Info message here');
});

logger is the name of the argument, appObj.get('logger') is its default value. logger是参数的名称, appObj.get('logger')是其默认值。

Also, you're using co() when there's no need to use it, and its likely causing the problem because it's executing the code inside the services function at the next tick of the event loop (ie it's calling app.set('logger', ...) after calling appObj.get('logger') ). 另外,您在不需要使用co()时会使用它,这很可能引起问题,因为它在事件循环的下一个app.set('logger', ...)即调用app.set('logger', ...)services函数中执行代码app.set('logger', ...) 调用appObj.get('logger') )之后。

Try this: 尝试这个:

module.exports = function appStartup() {
  app.use(cors());
  app.set('logger', winstonLogger);
  return app;
};

EDIT : if appStartup depends on something asynchronous, one solution would be to return a promise from it, and handle it "upstream": 编辑 :如果appStartup依赖于异步的东西,一种解决方案是从中返回一个承诺,并“上游”处理它:

module.exports = function appStartup() {
  app.use(cors());
  app.set('logger', winstonLogger);
  return mongo.connect().then(db => {
    app.db = db;
    return app;
  });
};

// server.js
const app = require('./src/appStartup');
const appPort = process.env.PORT;

app().then(appObj => {
  appObj.listen(appPort, (logger = appObj.get('logger')) => {
    logger.info('Info message here');
  });
}).catch(e => {
  console.error('Unable to create app', e);
  process.exit(1);
});

Or using async/await , which works on recent (8.x) Node.js versions: 或使用async/await ,它适用于最新(8.x)Node.js版本:

module.exports = async function appStartup() {
  app.use(cors());
  app.set('logger', winstonLogger);
  app.db = await mongo.connect();
  return app;
};

// server.js
const app     = require('./src/appStartup');
const appPort = process.env.PORT;

void async function() { // async IIFE
  try {
    var appObj = await app();
  } catch(e) {
    console.error('Unable to create app', e);
    process.exit(1);
  }
  appObj.listen(appPort, (logger = appObj.get('logger')) => {
    logger.info('Info message here');
  });
}();

It is an known issue with babel-eslint . babel-eslint是一个已知问题。 Try upgrading it to a latest version and it will resolve the issue. 尝试将其升级到最新版本,它将解决此问题。

Check this thread for more info 检查此线程以获取更多信息

As a temporary solution you may try considering rewriting your arrow function in es5 way. 作为临时解决方案,您可以尝试考虑以es5方式重写箭头功能。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM