Skip to content

Commit

Permalink
feat: use Koa router name as span name if available (#976)
Browse files Browse the repository at this point in the history
* feat: use Koa router name as span name if available

* feat: use Koa router name as span name if available (addressed feedback)

Co-authored-by: Rauno Viskus <[email protected]>
  • Loading branch information
lukiano and rauno56 authored Jun 22, 2022
1 parent a8c5c9f commit fa4fe9c
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export const getMiddlewareMetadata = (
[AttributeNames.KOA_TYPE]: KoaLayerType.ROUTER,
[SemanticAttributes.HTTP_ROUTE]: layerPath,
},
name: `router - ${layerPath}`,
name: context._matchedRouteName || `router - ${layerPath}`,
};
} else {
return {
Expand Down
50 changes: 50 additions & 0 deletions plugins/node/opentelemetry-instrumentation-koa/test/koa.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,56 @@ describe('Koa Instrumentation', () => {
);
});

it('should create a named child span for middlewares', async () => {
const rootSpan = tracer.startSpan('rootSpan');
const rpcMetadata = { type: RPCType.HTTP, span: rootSpan };
app.use((ctx, next) =>
context.with(
setRPCMetadata(
trace.setSpan(context.active(), rootSpan),
rpcMetadata
),
next
)
);

const router = new KoaRouter();
router.get('retrievePost', '/post/:id', ctx => {
ctx.body = `Post id: ${ctx.params.id}`;
});

app.use(router.routes());

await context.with(
trace.setSpan(context.active(), rootSpan),
async () => {
await httpRequest.get(`http://localhost:${port}/post/0`);
rootSpan.end();

assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 2);
const requestHandlerSpan = memoryExporter
.getFinishedSpans()
.find(span => span.name === 'retrievePost');
assert.notStrictEqual(requestHandlerSpan, undefined);

assert.strictEqual(
requestHandlerSpan?.attributes[AttributeNames.KOA_TYPE],
KoaLayerType.ROUTER
);

assert.strictEqual(
requestHandlerSpan?.attributes[SemanticAttributes.HTTP_ROUTE],
'/post/:id'
);

const exportedRootSpan = memoryExporter
.getFinishedSpans()
.find(span => span.name === 'GET /post/:id');
assert.notStrictEqual(exportedRootSpan, undefined);
}
);
});

it('should correctly instrument nested routers', async () => {
const rootSpan = tracer.startSpan('rootSpan');
const rpcMetadata = { type: RPCType.HTTP, span: rootSpan };
Expand Down

0 comments on commit fa4fe9c

Please sign in to comment.