[eggjs/egg]egg项目中如何开启阿里性能平台的 Trace 慢链路追踪

2024-07-22 578 views
6
Background

项目依赖egg框架,用alinode做的性能监控,alinode已开启,慢http日志已经有数据了,Trace一直无数据,按照阿里提供的文档https://help.aliyun.com/document_detail/72715.html,装入了文档里面的依赖,因为项目没有使用express,按照文档实例代码仿写一直未成功,请问有没有egg项目开启 Trace 的例子代码

Proposal

这是在一个接口里面仿写的一段代码 `async all_timeout() { const { ctx } = this;

let req=this.ctx.request;
req.parentSpan = tracer.startSpan('根模块');
req.parentSpan.setTag(opentracing.Tags.PEER_HOSTNAME, req.hostname);
req.parentSpan.setTag(opentracing.Tags.HTTP_METHOD, req.method.toUpperCase());
req.parentSpan.setTag(opentracing.Tags.HTTP_URL, req.url);

let res =await ctx.service.repository.getAll(3000)

req.parentSpan.setTag(opentracing.Tags.HTTP_STATUS_CODE, res.statusCode);
req.parentSpan.finish(req);

let spanName = `${ctx.method} ${ctx.url}`;
const spanOptions = {

  tags: {

    [opentracing.Tags.HTTP_METHOD]: ctx.method,

    [opentracing.Tags.HTTP_URL]: ctx.href,

  },

};
const span = tracer.startSpan(spanName, spanOptions)
span.setTag('span.kind', 'server');
span.finish(req);
this.ctx.body=res

}`

按此方法执行控制台会提示 span.finish without request will cause some problem, please use "span.finish(req)..."

回答

5

你这个写法完全不对,@alicloud/opentracing 这个包本质上是依赖父子 span 来确定链路,所以正常的写法是:

// 根 span
req.parentSpan = tracer.startSpan('根模块');
    // 第一层子 span1,注意不能省略 childOf,这个是申明父子 span 关系的
    const child1 = tracer.startSpan('子模块1', { childOf: req.parentSpan });
        // 第二层子 span1(如果有)
        const child1_child1 = tracer.startSpan('子模块1', { childOf: child1 });
        child1_child1.finish(req);
    child1.finish(req);

    // 第一层子 span2(如果有)
req.parentSpan.finish(req);

我这里用前后缩进来伪代码表示父子 span 申明的关系,你自己的代码中不需要这样,你可以结合官方的例子加上这段伪代码逻辑理解下这个逻辑

8

链路关系依赖 childOf 的申明,而且要对每个 span (根/子)都要在 start 后进行闭合

9

而 startSpan 只要定义好父子链路关系,可以在任意中间件/异步操作前后设置,和框架无关

0

@hyj1991 谢谢大佬

1

@atian25 感谢大佬,仔细看了这个插件,试试看

9

大佬,请问一下我按照父子关系包裹了一个 await ,现在慢日志写不进去了,控制台还是会提示 span.finish without request will cause some problem, please use "span.finish(req)...",请问有解吗

0

这个 warning 无所谓,egg ctx.request 好像不是直接继承 http.IncomingMessage 类,这里的判断本身也有问题

3

大佬有实例的代码片段的,能不能提供一个,我按照上面的代码写完部署在阿里node性能监测平台里面还是看不到 Trace 数据