简体   繁体   English

在文件之间导出 Nodejs 中的日志记录

[英]Export logging in Nodejs between files

I have two files in nodejs:我在nodejs中有两个文件:

  1. index.js
  2. function.js

The index.js is my main file in which i call the functions inside function.js . index.js是我的主文件,我在其中调用function.js中的函数。 In function.js i need to use logging, the problem is i didn't figure out how to use it.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 index.js

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

Will return将返回

app is not defined应用未定义

tried it without the app in the function.js it returned to me在没有 function.js 中的应用程序的情况下尝试它返回给我

log not defined.未定义日志。

I only need to use the app.log between the functions ( my main one the index.js and the function.js )我只需要在功能之间使用 app.log (我的主要功能是 index.js 和 function.js )

Pass as an argument作为参数传递

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

Then consume然后消费

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

To log in Node.js, you should use console https://nodejs.org/api/console.html要登录 Node.js,您应该使用控制台https://nodejs.org/api/console.html

Example例子

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

Consider extracting the log functionality out into its own file that can be referenced by function.js , index.js , and anything else in your app.考虑将日志功能提取到它自己的文件中,该文件可以被function.jsindex.js以及应用程序中的任何其他内容引用。 For example:例如:

logger.js logger.js

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

function.js function.js

var logger = require(“./log.js”);d

module.exports = {
  exampleFunction: function() {
    logger.log(“foo bar”);
  }
};

index.js index.js

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

functions.exampleFunction();
logger.log(“foo”);

You should send the logs off to a service like TrackJS to aggregate, report, and alert you to production problems.您应该将日志发送到TrackJS 之类的服务,以汇总、报告和提醒您生产问题。

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

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