所以我正在尝试通过我的Express应用程序实现X射线。 我有我的app.js文件,并且内部引用了一个路由器文件。
我的项目结构:
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())
})
我正在关注自动模式示例:通过AWS文档(https://docs.aws.amazon.com/xray-sdk-for-nodejs/latest/reference/index.html)中的异步函数调用进行捕获,但是出现一条错误消息: “无法从上下文中获取当前子/段。”
谁能让我知道我做错了吗?
答案 0 :(得分:1)
您应将app.use(AWSXRay.express.openSegment("MyApp"))
代码移到app.js
上方的app.use("/", indexRouter)
然后将app.use(AWSXRay.express.closeSegment())
移到app.use("/", indexRouter)
下方。
如果您查看提供的链接中引用的代码,则会发现openSegment
和closeSegment
不在路线之内,而不是在路线之内(因为您目前拥有它们)
链接中的代码以供参考:
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