简体   繁体   中英

AWS X-Ray with Node.JS Express and request

So I'm trying to implement X-Ray with my express app. I have my app.js file and inside reference a router file.

my project structure:
project/ routes/ index.js app.js

app.js:

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

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."


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)

Then move the app.use(AWSXRay.express.closeSegment()) below the 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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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