简体   繁体   English

如何写入Node.js Connect / Express记录器?

[英]How do I write to the Node.js Connect/Express logger?

I have an Express project and I have it set up to log to a file: 我有一个Express项目,我将其设置为登录到文件:

logPath = '/mnt/log/api.log'
logfile = fs.createWriteStream logPath, {flags: 'a'} 

loggingOptions = 
  format: 'default'
  stream: logfile

app.use express.logger(loggingOptions)

This works for logging requests, but I want to add my own messages to the log, but I can't figure out how. 这适用于记录请求,但我想将自己的消息添加到日志中,但我无法弄清楚如何。 console.log isn't redirected, and there doesn't seem to be a "logger" object created that I can write to. console.log没有被重定向,并且似乎没有创建我可以写入的“记录器”对象。

So is my only option to pass around a reference to the file stream and write to that? 那么我唯一的选择是传递对文件流的引用并写入该文件流?

I don't know how to do exactly what you are asking but this is what I do and so far it has worked well. 我不知道如何做到你所要求的,但这就是我所做的,到目前为止它运作良好。

I configure the express logger (which is actually the connect logger by the way if you are looking for documentation) like shown below and all the log output goes to stdout. 我配置了快速记录器(如果你正在查找文档,它实际上是连接记录器),如下所示,所有日志输出都转到stdout。 I can print to the same output with console.log("blah blah"). 我可以使用console.log(“blah blah”)打印到相同的输出。

app.use(express.logger("default"));

On the production server I redirect all the output of node to to the log file. 在生产服务器上,我将节点的所有输出重定向到日志文件。

This works well during development too because I run node in a shell window and can see all the same output. 这在开发期间也很有效,因为我在shell窗口中运行节点并且可以看到所有相同的输出。 (Actually I use express.logger("dev") during development because the output is much cleaner for dev work.) (实际上我在开发过程中使用了express.logger(“dev”),因为输出对开发工作来说要干净得多。)

You could create your own logging middleware: 您可以创建自己的日志记录中间件:

app.use (req, res, next) ->
   logFile.write "anything you want"
   next()

Define error-handling middleware like other middleware, except with four arguments instead of three, specifically with the signature (err, req, res, next)): 像其他中间件一样定义错误处理中间件,除了四个参数而不是三个,特别是签名(err,req,res,next)):

    app.use(function(err, req, res, next){
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

http://expressjs.com/guide/error-handling.html http://expressjs.com/guide/error-handling.html

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

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