node.js - AWS X-Ray 与 Node.JS Express 和请求
问题描述
所以我正在尝试用我的 express 应用程序实现 X-Ray。我有我的 app.js 文件并在内部引用了一个路由器文件。
我的项目结构:
project/
routes/
index.js
app.js
应用程序.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)中的异步函数调用捕获,但我我收到一条错误消息:“无法从上下文中获取当前子/段。”
谁能让我知道我做错了什么?
解决方案
你应该把app.use(AWSXRay.express.openSegment("MyApp"))
代码移到app.js
上面app.use("/", indexRouter)
然后将app.use(AWSXRay.express.closeSegment())
下面的app.use("/", indexRouter)
.
如果您查看提供的链接中引用的代码,您会注意到openSegment
andcloseSegment
在路线之外,而不是在路线内部(因为您目前拥有它们)
链接中的代码供参考:
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
推荐阅读
- postgresql - Windows 重置后是否可以在 pgadmin4 上获取数据库(保留文件选项)?
- echo - 如何将 gRPC 与 golang echo 框架一起使用?
- python - 如何连接 Harris 检测到的角以构建图形
- java - PDFBOX - 将 PDF UA 组合成 ON 大文件 - PDF UA 标签嵌套
- python-3.x - 未联系 Pgadmin 服务器
- android - 如何在 Android 中创建独立服务?
- java - 通过resteasy向spring boot应用程序发送multipartout的问题
- amazon-web-services - 将删除标记分配给对象后,在一段时间后完全删除 Amazon S3 中的对象
- tensorflow - 具有小训练集的多标签文本分类
- reactjs - Material UI - 使用 Root 和使用 ClassName 覆盖样式