【问题标题】:Expressjs Morgan dynamically format the logsExpressjs Morgan 动态格式化日志
【发布时间】:2014-09-17 15:50:52
【问题描述】:

尝试通过应用程序运行时更改摩根的日志记录格式。

该值将在数据库中的某个远程值上更改挂起,我希望摩根的输出因此而更改。 IE。如果在数据库中值为 1,摩根的格式为 'dev',如果值为 3,则格式为 'combined'

我一直在使用以下行来设置 morgan 的格式:

app.use(morgan(get_verbose()))
   .use ....

其中 get_verbose 将对应于格式选项。 然而,它并没有给出我想要的动态结果——它只是设置了一次格式。

我是在错误地处理这个问题,还是摩根在运行时仅限于 1 种格式?

【问题讨论】:

    标签: javascript node.js logging express


    【解决方案1】:

    一种方法是创建一个“包装” Morgan 中间件的中间件函数:

    var morganDev = mordan('dev');
    var morganCombined = morgan('combined');
    
    app.use(function(req, res, next) {
        var value = /* get value somehow */
    
        if (value === 1) {
            morganDev(req, res, next);
        } else if (value === 3) {
            morganCombined(req, res, next);
        }
    });
    

    首先,您为所需的每种日志格式创建一个记录器,但不要将它们中的任何一个附加到应用程序中。取而代之的是一个自定义函数读取该值并选择哪个记录器应处理此请求。

    安全更新:应该有一个包罗万象的else块来处理value既不是1也不是3的情况。这个块应该直接调用next(),否则请求处理将停止并且永远不会向客户端返回响应。

    【讨论】:

      【解决方案2】:

      使用 Morgan 的内置功能实现此目的的另一种方法是 skip 参数。来自documentation

      // EXAMPLE: only log error responses
      morgan('combined', {
        skip: function (req, res) { return res.statusCode < 400 }
      })
      

      skip 选项指定一个带有参数reqres 的函数,该函数返回True/False 以确定是否应跳过日志记录选项。该函数可以包含任何必要的代码,只要它返回TrueFalse

      根据您要区分登录的参数,这可能比多行 if/else 块更简单。将 HTTPS 流量与 HTTP 流量分开记录的示例服务器:

      const express = require('express');
      const http = require('http');
      const https = require('https');
      const logger = require('morgan');
      
      const httpsOptions = // {} hash of options.
      
      app.use(logger('combined', {
        stream: httpLogStream,
        skip: function(req, res) { return req.secure }
      });
      app.use(logger('combined', {
        stream: httpsLogStream,
        skip: function(req, res) { return !req.secure }
      });
      
      http.createServer(app).listen(80);
      https.createServer(httpsOptions, app).listen(443);
      

      可以在 here 找到我在此示例中所做的设置 HTTPS 的一个很好的演练。

      要了解 Express 的 req.secure 方法:here

      日志流设置为Morgan's documentation

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-24
        • 2017-02-05
        • 1970-01-01
        • 1970-01-01
        • 2019-03-31
        • 2015-09-20
        相关资源
        最近更新 更多