Skip to content

Commit

Permalink
chore(koa): migrate koa example to opentelemetry-instrumentation-koa (o…
Browse files Browse the repository at this point in the history
…pen-telemetry#1118)

* fix(migrate-koa-example): migrate koa example to opentelemetry-instrumentation-koa

* chore(koa): fix READMEs, versioning and imports

* chore(koa): remove redundant imports

* chore(koa): fix server imports

* chore(koa): add if to verity span exist
  • Loading branch information
haddasbronfman authored Aug 21, 2022
1 parent 44f9527 commit b406b1d
Show file tree
Hide file tree
Showing 14 changed files with 105 additions and 84 deletions.
1 change: 1 addition & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ For instance, examples of using `express` instrumentation have moved from this d
* [ ] Move the files
* [ ] Choose an instrumentation package to migrate examples for.
* [ ] Move the examples from `./examples/[name]` to `./plugins/[node or web]]/opentelemetry-instrumentation-[name]/examples`.
* [ ] Update the `./plugins/[node or web]]/opentelemetry-instrumentation-[name]/README.md` and replace the path `examples/[name]` with the new path of the examples.
* [ ] Update the `package.json` in the examples folder
* [ ] Remove the `@opentelemetry/instrumentation-[name]` dependency.
* [ ] Install `typescript` and `ts-node` in the examples directory.
Expand Down
44 changes: 0 additions & 44 deletions examples/koa/tracer.js

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ registerInstrumentations({
});
```

See [examples/express](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/plugins/node/opentelemetry-instrumentation-express/examples) for a short example.
See [examples](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/plugins/node/opentelemetry-instrumentation-express/examples) for a short example.

### Caveats

Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
build
examples
2 changes: 1 addition & 1 deletion plugins/node/opentelemetry-instrumentation-koa/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ registerInstrumentations({
});
```

See [`examples/koa`](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/examples/koa) for a short example using both Koa and @koa/router
See [`examples`](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/plugins/node/opentelemetry-instrumentation-koa/examples) for a short example using both Koa and @koa/router

### Koa Instrumentation Options

Expand Down
File renamed without changes.
File renamed without changes
File renamed without changes
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@
"description": "Example of Koa and @koa/router integration with OpenTelemetry",
"main": "index.js",
"scripts": {
"zipkin:server": "cross-env EXPORTER=zipkin node ./server.js",
"zipkin:client": "cross-env EXPORTER=zipkin node ./client.js",
"jaeger:server": "cross-env EXPORTER=jaeger node ./server.js",
"jaeger:client": "cross-env EXPORTER=jaeger node ./client.js",
"lint": "eslint . --ext .js",
"lint:fix": "eslint . --ext .js --fix"
"zipkin:server": "cross-env EXPORTER=zipkin ts-node src/server.ts",
"zipkin:client": "cross-env EXPORTER=zipkin ts-node src/client.ts",
"jaeger:server": "cross-env EXPORTER=jaeger ts-node src/server.ts",
"jaeger:client": "cross-env EXPORTER=jaeger ts-node src/client.ts",
"compile": "tsc -p ."
},
"repository": {
"type": "git",
Expand All @@ -32,20 +31,22 @@
},
"dependencies": {
"@koa/router": "^9.3.1",
"@opentelemetry/api": "^1.0.2",
"@opentelemetry/exporter-jaeger": "^0.25.0",
"@opentelemetry/exporter-zipkin": "^0.25.0",
"@opentelemetry/instrumentation": "^0.25.0",
"@opentelemetry/instrumentation-http": "^0.25.0",
"@opentelemetry/instrumentation-koa": "^0.23.0",
"@opentelemetry/sdk-trace-node": "^0.25.0",
"@opentelemetry/sdk-trace-base": "^0.25.0",
"@opentelemetry/api": "^1.0.0",
"@opentelemetry/exporter-jaeger": "^1.0.0",
"@opentelemetry/exporter-zipkin": "^1.0.0",
"@opentelemetry/instrumentation": "^0.31.0",
"@opentelemetry/instrumentation-http": "^0.31.0",
"@opentelemetry/instrumentation-koa": "^0.31.0",
"@opentelemetry/sdk-trace-node": "^1.0.0",
"@opentelemetry/sdk-trace-base": "^1.0.0",
"axios": "^0.21.1",
"koa": "^2.13.0"
},
"homepage": "https://github.com/open-telemetry/opentelemetry-js-contrib#readme",
"devDependencies": {
"cross-env": "^6.0.0",
"eslint": "^7.4.0"
"ts-node": "^10.6.0",
"typescript": "^4.6.2",
"@types/koa": "^2.13.5"
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
'use strict';

// eslint-disable-next-line import/order
const tracer = require('./tracer')('example-koa-client');
const api = require('@opentelemetry/api');
const axios = require('axios').default;
import { setupTracing } from "./tracer";
const tracer = setupTracing('example-koa-client');
import * as api from '@opentelemetry/api';
import { default as axios } from 'axios';

function makeRequest() {
const span = tracer.startSpan('client.makeRequest()', {
Expand All @@ -16,7 +16,9 @@ function makeRequest() {
span.setStatus({ code: api.SpanStatusCode.OK });
console.log(res.statusText);
} catch (e) {
span.setStatus({ code: api.SpanStatusCode.ERROR, message: e.message });
if(e instanceof Error) {
span.setStatus({ code: api.SpanStatusCode.ERROR, message: e.message });
}
}
span.end();
console.log('Sleeping 5 seconds before shutdown to ensure all records are flushed.');
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
'use strict';

const api = require('@opentelemetry/api');

require('./tracer')('example-koa-server');
import * as api from '@opentelemetry/api';
import { setupTracing } from './tracer'
setupTracing('example-koa-server');

// Adding Koa router (if desired)
const router = require('@koa/router')();
const Koa = require('koa');
import * as Router from "@koa/router";
import * as Koa from "koa"


// Setup koa
const app = new Koa();
const PORT = 8081;
const router = new Router();

// route definitions
router.get('/run_test', runTest)
Expand All @@ -27,16 +29,17 @@ async function setUp() {
*/
const posts = ['post 0', 'post 1', 'post 2'];

function addPost(ctx) {
posts.push(`post ${posts.length}`);
function addPost(ctx: Koa.Context) {
const newPostId = posts.length;
posts.push(`post ${newPostId}`);
const currentSpan = api.trace.getSpan(api.context.active());
currentSpan.addEvent('Added post');
currentSpan.setAttribute('Date', new Date());
currentSpan?.addEvent('Added post');
currentSpan?.setAttribute('post.id', newPostId)
ctx.body = `Added post: ${posts[posts.length - 1]}`;
ctx.redirect('/post/3');
}

async function showNewPost(ctx) {
async function showNewPost(ctx: Koa.Context) {
const { id } = ctx.params;
console.log(`showNewPost with id: ${id}`);
const post = posts[id];
Expand All @@ -46,18 +49,20 @@ async function showNewPost(ctx) {
ctx.body = post;
}

function runTest(ctx) {
function runTest(ctx: Koa.Context) {
console.log('runTest');
const currentSpan = api.trace.getSpan(api.context.active());
const { traceId } = currentSpan.spanContext();
console.log(`traceid: ${traceId}`);
console.log(`Jaeger URL: http://localhost:16686/trace/${traceId}`);
console.log(`Zipkin URL: http://localhost:9411/zipkin/traces/${traceId}`);
ctx.body = `All posts: ${posts}`;
ctx.redirect('/post/new');
if (currentSpan){
const { traceId } = currentSpan.spanContext();
console.log(`traceid: ${traceId}`);
console.log(`Jaeger URL: http://localhost:16686/trace/${traceId}`);
console.log(`Zipkin URL: http://localhost:9411/zipkin/traces/${traceId}`);
ctx.body = `All posts: ${posts}`;
ctx.redirect('/post/new');
}
}

async function noOp(ctx, next) {
async function noOp(ctx: Koa.Context, next: Koa.Next) {
console.log('Sample basic koa middleware');
const syntheticDelay = 100;
await new Promise((r) => setTimeout(r, syntheticDelay));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
'use strict';

import { KoaInstrumentation } from '@opentelemetry/instrumentation-koa';
import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';

import * as api from '@opentelemetry/api';
import { registerInstrumentations } from '@opentelemetry/instrumentation';
import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';
import { JaegerExporter } from '@opentelemetry/exporter-jaeger';
import { ZipkinExporter } from '@opentelemetry/exporter-zipkin';
import { Resource } from '@opentelemetry/resources';
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions'

const EXPORTER = process.env.EXPORTER || '';

export const setupTracing = (serviceName: string) => {
const provider = new NodeTracerProvider({
resource: new Resource({
[SemanticResourceAttributes.SERVICE_NAME]: serviceName
})
});

let exporter;
if (EXPORTER === 'jaeger') {
exporter = new JaegerExporter();
} else {
exporter = new ZipkinExporter();
}
provider.addSpanProcessor(new SimpleSpanProcessor(exporter));

registerInstrumentations({
instrumentations: [
new KoaInstrumentation(),
new HttpInstrumentation(),
],
tracerProvider: provider,
});

// Initialize the OpenTelemetry APIs to use the NodeTracerProvider bindings
provider.register();

return api.trace.getTracer(serviceName);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"noEmit": true,
"rootDir": ".",
},
"include": [
"src/**/*.ts",
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"prewatch": "npm run precompile",
"version:update": "node ../../../scripts/version-update.js",
"compile": "tsc -p .",
"compile:examples": "cd examples && npm run compile",
"prepare": "npm run compile",
"watch": "tsc -w"
},
Expand Down

0 comments on commit b406b1d

Please sign in to comment.