【问题标题】:Export logging in Nodejs between files在文件之间导出 Nodejs 中的日志记录
【发布时间】:2020-02-10 20:11:54
【问题描述】:

我在 nodejs 中有两个文件:

  1. index.js
  2. function.js

index.js 是我的主文件,我在其中调用function.js 中的函数。在function.js我需要使用日志,问题是我没有弄清楚如何使用它。

function.js

module.exports = {

Exemplfunciton: async () => {
    app.log('#### This is just an exemple im trying to run')
    }

checkCalcul:async(a,b) = > {
log.(`The Val of A : ${a}, the Val of B: ${b}`
return a+b
}
}

index.js

const functionToCall = require('/function.js)
module.exports = app => { 
functionToCall.Exemplfunciton()
functionToCall.checkCalcul(4,5)
}

会回来

应用未定义

在它返回给我的 function.js 中没有应用程序的情况下尝试过

未定义日志。

我只需要在函数之间使用app.log(我主要的是index.js和function.js)

【问题讨论】:

    标签: javascript node.js logging


    【解决方案1】:

    作为参数传递

    module.exports = app => { 
       functionToCall.Exemplfunciton(app) // add here
    }
    

    然后消费

    module.exports = {
        Exemplfunciton: async (app) => { // add here
            app.log('#### This is just an exemple im trying to run')
        }
    }
    

    【讨论】:

      【解决方案2】:

      要登录Node.js,你应该使用控制台https://nodejs.org/api/console.html

      示例

      module.exports = {
      
      ExampleFunction: async () => {
          console.log('#### This is just an example I\'m trying to run')
          }
      }
      
      const functionToCall = require('./function.js')
      functionToCall.ExampleFunction() // logs #### This is just an example I\'m trying to run
      

      【讨论】:

      • 对不起,如果您不理解我的问题,我不想使用 console.log,但我想在 index.js 中使用应用程序日志,我想得到我的日志记录错误在服务器中。当我的函数在 index.js 中时,我能够执行 app.log,但是当我将它们拆分为两个文件并从 function.js 调用它们时,应用程序日志变得未定义,因为它只存在于 index.js
      • 您可以编辑您的帖子以包含您想要使用的每个变量吗?喜欢应用。
      【解决方案3】:

      考虑将日志功能提取到它自己的文件中,function.jsindex.js 以及您应用中的任何其他内容都可以引用该文件。例如:

      logger.js

      module.exports = {
        log: function() {
          /* aggregate logs and send to your logging service, like TrackJS.com */
        }
      }
      

      function.js

      var logger = require(“./log.js”);d
      
      module.exports = {
        exampleFunction: function() {
          logger.log(“foo bar”);
        }
      };
      

      index.js

      var functions = require(“./functions.js”);
      var logger = require(“./log.js”);
      
      functions.exampleFunction();
      logger.log(“foo”);
      

      您应该将日志发送到TrackJS to aggregate, report, and alert 这样的服务以解决生产问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-03-26
        • 2015-03-11
        • 1970-01-01
        • 2017-03-02
        • 1970-01-01
        • 2021-01-29
        • 2017-06-20
        相关资源
        最近更新 更多