参考资料
- https://community.aws/tutorials/solving-problems-you-cant-see-using-aws-x-ray-and-cloudwatch-for-user-level-observability-in-your-serverless-microservices-applications
- https://stackoverflow.com/questions/76000811/search-cloudwatch-logs-for-aws-xray-trace-id-in-code
ecs容器环境下应用生成的trace信息没有log关联,但是在lambda环境中测试时发现可以进行关联
检查发现,trace的rawdata中存在aws的cwlog字段
在控制台查看网络请求,此时会向cloudwatchlog服务发送log insight请求
当我们在控制台点击跳转到loginsight时,语句如下。
fields @log, @timestamp, @message
| filter @message like "1-66570681-3cb9b1bc917ab87c3dd8b303" or @message like "665706813cb9b1bc917ab87c3dd8b303"
| sort @timestamp, @message desc
经过以上步骤我们对两个问题有所了解
- xray如何找到日志组?通过aws.cloudwatch_log属性
- log如何呈现在xray控制台?通过发送loginsight的xhr请求
那么,接下来我们需要考虑如何在ecs应用中实现以上条件。参考链接(https://stackoverflow.com/questions/76000811/search-cloudwatch-logs-for-aws-xray-trace-id-in-code)中的说明
For API Gateway, Lambdas, the application logs group name are embedded in X-Ray traces out of box, so you don't need to do anything specially.
For the trace Id injection to application logs, today it is only supported by X-Ray/OTel Java SDKs. For Javascript applications, you'll need to inject and print X-Ray trace ids
AWS-XRAY-TRACE-ID: 1-5d77f256-19f12e4eaa02e3f76c78f46a
to your application log entries yourself.
对于条件1,我们需要编辑segment,加入aws.cloudwatch_log属性
对于条件2,我们需要在log内容中注入traceID
参考链接(https://blog.csdn.net/sinat_41567654/article/details/129317614)中的步骤创建xray和ecs集成环境,加入以下额外逻辑
- 在segment中加入aws.cloudwatch_log属性
- 模拟输出了一条日志并嵌入traceID
js
app.get('/', (req, res) => {
var document = AWSXRay.getSegment();
// 加入aws.cloudwatch_log属性
document.aws.cloudwatch_logs = [
{
"log_group": "/ecs/ecs-xray-demo-fargaet"
}
]
traceId = document.trace_id;
console.log(document)
// 模拟输出了一条日志并嵌入traceID
console.log("2019-09-10 18:58:30.844 [nio-5000-exec-4] AWS-XRAY-TRACE-ID: " + traceId + " WARN 1 - Your logging message here")
})
app.use(AWSXRay.express.closeSegment());
查看ecs的应用日志如下,trace和log成功关联
查看xray服务的控制台成功实现关联