简体   繁体   English

带有Node.JS Express的AWS X-Ray和请求

[英]AWS X-Ray with Node.JS Express and request

So I'm trying to implement X-Ray with my express app. 因此,我正在尝试通过我的Express应用程序实现X射线。 I have my app.js file and inside reference a router file. 我有我的app.js文件,并且内部引用了一个路由器文件。

my project structure: 我的项目结构:
project/ routes/ index.js app.js

app.js: app.js:

var indexRouter = require("./routes/index")
...
app.use("/", indexRouter)
...

index.js: index.js:

const AWSXRay = require("aws-xray-sdk")
const request = require("request")

router.post("/xray", async function(req, res, next) {
    let app = req.app
    app.use(AWSXRay.express.openSegment("MyApp"))

    try {
        console.log(AWSXRay.getSegment()) // this succesfully gets segment
        AWSXRay.captureAsyncFunc("send", function(subsegment) {
            request.get("http://www.google.com", { XRaySegment: subsegment }, function() {
                res.json({
                    success: "success"
                })
                subsegment.close()
        })
    } catch (err) {
        next(err)
    }
    app.use(AWSXRay.express.closeSegment())
})

I'm following the automatic mode examples: Capture through async function calls from the AWS documentation ( https://docs.aws.amazon.com/xray-sdk-for-nodejs/latest/reference/index.html ), but I am getting a error that says: "Failed to get the current sub/segment from the context." 我正在关注自动模式示例:通过AWS文档( https://docs.aws.amazon.com/xray-sdk-for-nodejs/latest/reference/index.html )中的异步函数调用进行捕获,但是我出现错误消息:“无法从上下文中获取当前子/段。”


Can anyone let me know what I am doing wrong? 谁能让我知道我在做什么错?

You should move the app.use(AWSXRay.express.openSegment("MyApp")) code to the app.js above the app.use("/", indexRouter) 您应该将app.use(AWSXRay.express.openSegment("MyApp"))代码移动到app.use("/", indexRouter)上方的app.js

Then move the app.use(AWSXRay.express.closeSegment()) below the app.use("/", indexRouter) . 然后将app.use(AWSXRay.express.closeSegment())移动到app.use(AWSXRay.express.closeSegment()) app.use("/", indexRouter)

If you look at the code referenced in the link provided, you'll notice the openSegment and closeSegment are outside the route, not inside (as you have them currently) 如果您查看提供的链接中引用的代码,则会注意到openSegmentcloseSegment在路线之外,而不是在路线内(因为您当前拥有它们)

Code in link for reference: 链接中的代码可供参考:

var app = express();

//...

var AWSXRay = require('aws-xray-sdk');

app.use(AWSXRay.express.openSegment('defaultName'));               //required at the start of your routes

app.get('/', function (req, res) {
  res.render('index');
});

app.use(AWSXRay.express.closeSegment());   //Required at the end of your routes / first in error handling routes

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

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