Skip to content

Commit 8786cbe

Browse files
andyflemingFlarnarauno56
authored
chore: moves express examples into its package to establish pattern (open-telemetry#939)
* chore: moves express examples into its package to establish pattern * revert: unintentional path change * fix: uses more correct value * chore: bumps dependency versions * Adds instructions for migrating examples * Update plugins/node/opentelemetry-instrumentation-express/examples/package.json Co-authored-by: Gerhard Stöbich <[email protected]> * Update plugins/node/opentelemetry-instrumentation-express/examples/package.json Co-authored-by: Gerhard Stöbich <[email protected]> * ignores examples from lint * removes extra line * bumps otel dependency versions * cleanup * updates to use package name instead of relative path * updates CI approach to use lerna run command * bumps dependency versions Co-authored-by: Gerhard Stöbich <[email protected]> Co-authored-by: Rauno Viskus <[email protected]>
1 parent c5b9356 commit 8786cbe

File tree

15 files changed

+144
-74
lines changed

15 files changed

+144
-74
lines changed

.github/workflows/unit-test.yml

+2
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,8 @@ jobs:
153153
run: npx lerna bootstrap --no-ci --hoist --nohoist='zone.js' --nohoist='mocha' --nohoist='ts-mocha'
154154
- name: Unit tests
155155
run: npm run test:ci:changed -- ${{ matrix.lerna-extra-args }}
156+
- name: Build examples
157+
run: npm run compile:examples
156158
- name: Report Coverage
157159
if: matrix.node == '14'
158160
uses: codecov/codecov-action@v3

examples/README.md

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Instrumentation Examples
2+
3+
:warning: Note: We are working on migrating these examples to their respective package directories.
4+
5+
For instance, examples of using `express` instrumentation have moved from this directory to [plugins/node/opentelemetry-instrumentation-express](https://github.com/open-telemetry/opentelemetry-js/tree/main/plugins/node/opentelemetry-instrumentation-express).
6+
7+
## Instructions for Migrating an Example
8+
9+
* [ ] Move the files
10+
* [ ] Choose an instrumentation package to migrate examples for.
11+
* [ ] Move the examples from `./examples/[name]` to `./plugins/[node or web]]/opentelemetry-instrumentation-[name]/examples`.
12+
* [ ] Update the `package.json` in the examples folder
13+
* [ ] Remove the `@opentelemetry/instrumentation-[name]` dependency.
14+
* [ ] Install `typescript` and `ts-node` in the examples directory.
15+
* [ ] Replace usage of `node` in scripts with `ts-node`.
16+
* [ ] Add a script for compiling the code in scripts: `"compile": "tsc -p ."`
17+
* [ ] Add a tsconfig.json file in the examples folder. (Example below)
18+
* [ ] Update the code
19+
* [ ] Change code to use a relative import of the library.
20+
* [ ] Add types to the code
21+
* [ ] Update the instrumentation package's `package.json`
22+
* [ ] Add a script `"compile:examples": "cd examples && npm run compile",`.
23+
* [ ] Test the updated code
24+
* [ ] Test building the examples by running `npm run compile:examples`
25+
* [ ] Test that the actual exapmle code runs as expected
26+
27+
Example tsconfig.json file:
28+
29+
```json
30+
{
31+
"extends": "../tsconfig.json",
32+
"compilerOptions": {
33+
"noEmit": true,
34+
"rootDir": ".",
35+
},
36+
"include": [
37+
"src/**/*.ts",
38+
]
39+
}
40+
```

examples/express/package.json

-47
This file was deleted.

lerna.json

+2
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@
44
"packages/*",
55
"metapackages/*",
66
"plugins/node/*",
7+
"plugins/node/*/examples",
78
"plugins/web/*",
9+
"plugins/web/*/examples",
810
"propagators/*",
911
"detectors/node/*"
1012
],

package.json

+1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
"precompile": "tsc --version && npm run version:update",
1919
"version:update": "lerna run version:update",
2020
"compile": "lerna run compile",
21+
"compile:examples": "lerna run compile:examples",
2122
"prewatch": "npm run precompile",
2223
"test": "lerna run test",
2324
"test:ci:changed": "lerna run test --since origin/main",
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
build
2+
examples
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
{
2+
"name": "express-example",
3+
"private": true,
4+
"version": "0.28.0",
5+
"description": "Example of Express integration with OpenTelemetry",
6+
"main": "index.js",
7+
"scripts": {
8+
"zipkin:server": "cross-env EXPORTER=zipkin ts-node src/server.ts",
9+
"zipkin:client": "cross-env EXPORTER=zipkin ts-node src/client.ts",
10+
"jaeger:server": "cross-env EXPORTER=jaeger ts-node src/server.ts",
11+
"jaeger:client": "cross-env EXPORTER=jaeger ts-node src/client.ts",
12+
"compile": "tsc -p ."
13+
},
14+
"repository": {
15+
"type": "git",
16+
"url": "git+ssh://[email protected]/open-telemetry/opentelemetry-js.git"
17+
},
18+
"keywords": [
19+
"opentelemetry",
20+
"express",
21+
"tracing"
22+
],
23+
"engines": {
24+
"node": ">=8"
25+
},
26+
"author": "OpenTelemetry Authors",
27+
"license": "Apache-2.0",
28+
"bugs": {
29+
"url": "https://github.com/open-telemetry/opentelemetry-js/issues"
30+
},
31+
"dependencies": {
32+
"@opentelemetry/api": "^1.0.4",
33+
"@opentelemetry/exporter-jaeger": "^1.1.1",
34+
"@opentelemetry/exporter-zipkin": "^1.1.1",
35+
"@opentelemetry/instrumentation": "^0.27.0",
36+
"@opentelemetry/instrumentation-express": "^0.28.0",
37+
"@opentelemetry/instrumentation-http": "^0.27.0",
38+
"@opentelemetry/resources": "^1.1.1",
39+
"@opentelemetry/sdk-trace-base": "^1.1.1",
40+
"@opentelemetry/sdk-trace-node": "^1.1.1",
41+
"@opentelemetry/semantic-conventions": "^1.1.1",
42+
"axios": "^0.21.1",
43+
"cross-env": "^7.0.3",
44+
"express": "^4.17.1"
45+
},
46+
"homepage": "https://github.com/open-telemetry/opentelemetry-js#readme",
47+
"devDependencies": {
48+
"@types/express": "^4.17.13",
49+
"ts-node": "^10.6.0",
50+
"typescript": "^4.6.2"
51+
}
52+
}

examples/express/client.js plugins/node/opentelemetry-instrumentation-express/examples/src/client.ts

+9-5
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
'use strict';
22

33
// eslint-disable-next-line import/order
4-
const tracer = require('./tracer')('example-express-client');
5-
const api = require('@opentelemetry/api');
6-
const axios = require('axios').default;
4+
import { setupTracing } from "./tracer";
5+
const tracer = setupTracing('example-express-client');
6+
7+
import * as api from '@opentelemetry/api';
8+
import { default as axios } from 'axios';
79

810
function makeRequest() {
911
const span = tracer.startSpan('client.makeRequest()', {
@@ -16,8 +18,10 @@ function makeRequest() {
1618
console.log('status:', res.statusText);
1719
span.setStatus({ code: api.SpanStatusCode.OK });
1820
} catch (e) {
19-
console.log('failed:', e.message);
20-
span.setStatus({ code: api.SpanStatusCode.ERROR, message: e.message });
21+
if (e instanceof Error) {
22+
console.log('failed:', e.message);
23+
span.setStatus({ code: api.SpanStatusCode.ERROR, message: e.message });
24+
}
2125
}
2226
span.end();
2327
console.log('Sleeping 5 seconds before shutdown to ensure all records are flushed.');

examples/express/server.js plugins/node/opentelemetry-instrumentation-express/examples/src/server.ts

+7-7
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,19 @@
1-
'use strict';
1+
import { setupTracing } from './tracer'
22

3-
// eslint-disable-next-line
4-
require('./tracer')('example-express-server');
3+
setupTracing('example-express-server');
54

65
// Require in rest of modules
7-
const express = require('express');
8-
const axios = require('axios').default;
6+
import * as express from 'express';
7+
import { default as axios } from 'axios';
8+
import { RequestHandler } from "express";
99

1010
// Setup express
1111
const app = express();
1212
const PORT = 8080;
1313

1414
const getCrudController = () => {
1515
const router = express.Router();
16-
const resources = [];
16+
const resources: any[] = [];
1717
router.get('/', (req, res) => res.send(resources));
1818
router.post('/', (req, res) => {
1919
resources.push(req.body);
@@ -22,7 +22,7 @@ const getCrudController = () => {
2222
return router;
2323
};
2424

25-
const authMiddleware = (req, res, next) => {
25+
const authMiddleware: RequestHandler = (req, res, next) => {
2626
const { authorization } = req.headers;
2727
if (authorization && authorization.includes('secret_token')) {
2828
next();

examples/express/tracer.js plugins/node/opentelemetry-instrumentation-express/examples/src/tracer.ts

+19-15
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,28 @@
11
'use strict';
22

3+
import { Sampler, SpanKind } from "@opentelemetry/api";
4+
35
const opentelemetry = require('@opentelemetry/api');
46

57
// Not functionally required but gives some insight what happens behind the scenes
68
const { diag, DiagConsoleLogger, DiagLogLevel } = opentelemetry;
79
diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.INFO);
810

9-
const { AlwaysOnSampler } = require('@opentelemetry/core');
10-
const { registerInstrumentations } = require('@opentelemetry/instrumentation');
11-
const { NodeTracerProvider } = require('@opentelemetry/sdk-trace-node');
12-
const { SimpleSpanProcessor } = require('@opentelemetry/sdk-trace-base');
13-
const { JaegerExporter } = require('@opentelemetry/exporter-jaeger');
14-
const { ZipkinExporter } = require('@opentelemetry/exporter-zipkin');
15-
const { Resource } = require('@opentelemetry/resources');
16-
const { SemanticAttributes, SemanticResourceAttributes: ResourceAttributesSC } = require('@opentelemetry/semantic-conventions');
11+
import { AlwaysOnSampler } from '@opentelemetry/core';
12+
import { registerInstrumentations } from '@opentelemetry/instrumentation';
13+
import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
14+
import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';
15+
import { JaegerExporter } from '@opentelemetry/exporter-jaeger';
16+
import { ZipkinExporter } from '@opentelemetry/exporter-zipkin';
17+
import { Resource } from '@opentelemetry/resources';
18+
import { SemanticAttributes, SemanticResourceAttributes as ResourceAttributesSC } from '@opentelemetry/semantic-conventions';
19+
import { SpanAttributes } from "@opentelemetry/api/build/src/trace/attributes";
1720

18-
const Exporter = (process.env.EXPORTER || '')
19-
.toLowerCase().startsWith('z') ? ZipkinExporter : JaegerExporter;
20-
const { ExpressInstrumentation } = require('@opentelemetry/instrumentation-express');
21+
const Exporter = (process.env.EXPORTER || '').toLowerCase().startsWith('z') ? ZipkinExporter : JaegerExporter;
22+
import { ExpressInstrumentation } from '@opentelemetry/instrumentation-express';
2123
const { HttpInstrumentation } = require('@opentelemetry/instrumentation-http');
2224

23-
module.exports = (serviceName) => {
25+
export const setupTracing = (serviceName: string) => {
2426
const provider = new NodeTracerProvider({
2527
resource: new Resource({
2628
[ResourceAttributesSC.SERVICE_NAME]: serviceName,
@@ -45,10 +47,12 @@ module.exports = (serviceName) => {
4547
// Initialize the OpenTelemetry APIs to use the NodeTracerProvider bindings
4648
provider.register();
4749

48-
return opentelemetry.trace.getTracer('express-example');
50+
return opentelemetry.trace.getTracer(serviceName);
4951
};
5052

51-
function filterSampler(filterFn, parent) {
53+
type FilterFunction = (spanName: string, spanKind: SpanKind, attributes: SpanAttributes) => boolean;
54+
55+
function filterSampler(filterFn: FilterFunction, parent: Sampler): Sampler {
5256
return {
5357
shouldSample(ctx, tid, spanName, spanKind, attr, links) {
5458
if (!filterFn(spanName, spanKind, attr)) {
@@ -62,6 +66,6 @@ function filterSampler(filterFn, parent) {
6266
}
6367
}
6468

65-
function ignoreHealthCheck(spanName, spanKind, attributes) {
69+
function ignoreHealthCheck(spanName: string, spanKind: SpanKind, attributes: SpanAttributes) {
6670
return spanKind !== opentelemetry.SpanKind.SERVER || attributes[SemanticAttributes.HTTP_ROUTE] !== "/health";
6771
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
{
2+
"extends": "../tsconfig.json",
3+
"compilerOptions": {
4+
"noEmit": true,
5+
"rootDir": ".",
6+
},
7+
"include": [
8+
"src/**/*.ts",
9+
]
10+
}

plugins/node/opentelemetry-instrumentation-express/package.json

+1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
"prewatch": "npm run precompile",
1717
"version:update": "node ../../../scripts/version-update.js",
1818
"compile": "tsc -p .",
19+
"compile:examples": "cd examples && npm run compile",
1920
"prepare": "npm run compile",
2021
"watch": "tsc -w"
2122
},

0 commit comments

Comments
 (0)