【问题标题】:How to make console.log() to write to a file in hapi.js如何使 console.log() 写入 hapi.js 中的文件
【发布时间】:2018-05-30 14:29:00
【问题描述】:

我已经使用 Hapi.js 创建了一个应用程序,并且我使用了 good-file 将日志写入文件,并且当我使用 request.log() 和 server.log() 方法时,它会将日志写入文件.但我的要求是,当我使用 console.log() 时,它应该将其记录到文件中。因为我的所有文件中都没有请求或服务器对象。我怎样才能实现它?

这就是我配置记者的方式

myFileReporter: [{
    "module": "good-squeeze",
    "name": "Squeeze",
    "args": [{ 
        "request": "*", 
        "error": "*", 
        "response":"*",
        "log":"*"
    }]},
   {
        "module": "good-squeeze",
        "name": "SafeJson"
   }, 
   {
        "module": "good-file",
        "args": ["./logs/log"]
   }]

【问题讨论】:

    标签: javascript node.js npm hapijs


    【解决方案1】:

    由于 console.log 具有预定义的行为,您要么需要覆盖它,要么创建一个新函数。例如:

    const debugLog = (content) => {
        request.log(content);
        console.log(content);
    };
    

    【讨论】:

      【解决方案2】:

      来自this answerLudovic Feltz...

      // define a new console
      var console=(function(oldCons){
          return {
              log: function(text){
                  oldCons.log(text);
                  // Your logging code here
              },
              info: function (text) {
                  oldCons.info(text);
              },
              warn: function (text) {
                  oldCons.warn(text);
              },
              error: function (text) {
                  oldCons.error(text);
              }
          };
      }(window.console));
      
      //Then redefine the old console
      window.console = console;
      

      这使您可以继续使用console.log,同时保持其原始功能以及您的修改。

      【讨论】:

        【解决方案3】:

        我认为最好的解决方案是在您要登录的函数中提供服务器对象。

        你能告诉我更多吗?

        使用custom plug in,您几乎可以让服务器对象随处可用

        【讨论】:

          猜你喜欢
          • 2018-03-09
          • 2016-08-01
          • 2014-05-22
          • 2017-06-19
          • 1970-01-01
          • 2021-05-27
          • 2016-02-06
          • 2011-03-04
          • 2011-08-06
          相关资源
          最近更新 更多