Skip to content

Commit

Permalink
move express example (haven't adjusted build / docs yet)
Browse files Browse the repository at this point in the history
  • Loading branch information
trentm committed Feb 21, 2024
1 parent 5edcef2 commit 0cc9047
Show file tree
Hide file tree
Showing 8 changed files with 302 additions and 0 deletions.
82 changes: 82 additions & 0 deletions examples/express/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
# Overview

OpenTelemetry Express Instrumentation allows the user to automatically collect trace data and export them to the backend of choice (we can use Zipkin or Jaeger for this example), to give observability to distributed systems.

This is a simple example that demonstrates tracing calls made to Express API. The example
shows key aspects of tracing such as

- Root Span (on Client)
- Child Span (on Client)
- Span Events
- Span Attributes

## Installation

```sh
# from this directory, install all necessary dependencies from the workspace
npm run setup

# OR alternatively, install dependencies from npm as a standalone example app
npm install --workspaces=false
```

Setup [Zipkin Tracing](https://zipkin.io/pages/quickstart.html)
or
Setup [Jaeger Tracing](https://www.jaegertracing.io/docs/latest/getting-started/#all-in-one)

## Run the Application

### Zipkin

- Run the server

```sh
# from this directory
$ npm run zipkin:server
```

- Run the client

```sh
# from this directory
npm run zipkin:client
```

#### Zipkin UI

`zipkin:server` script should output the `traceid` in the terminal (e.g `traceid: 4815c3d576d930189725f1f1d1bdfcc6`).
Go to Zipkin with your browser <http://localhost:9411/zipkin/traces/(your-trace-id)> (e.g <http://localhost:9411/zipkin/traces/4815c3d576d930189725f1f1d1bdfcc6>)

<p align="center"><img src="./images/zipkin.jpg?raw=true"/></p>

### Jaeger

- Run the server

```sh
# from this directory
$ npm run jaeger:server
```

- Run the client

```sh
# from this directory
npm run jaeger:client
```

#### Jaeger UI

`jaeger:server` script should output the `traceid` in the terminal (e.g `traceid: 4815c3d576d930189725f1f1d1bdfcc6`).
Go to Jaeger with your browser <http://localhost:16686/trace/(your-trace-id)> (e.g <http://localhost:16686/trace/4815c3d576d930189725f1f1d1bdfcc6>)

<p align="center"><img src="images/jaeger.jpg?raw=true"/></p>

## Useful links

- For more information on OpenTelemetry, visit: <https://opentelemetry.io/>
- For more information on OpenTelemetry for Node.js, visit: <https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-sdk-trace-node>

## LICENSE

Apache License 2.0
Binary file added examples/express/images/jaeger.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/express/images/zipkin.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
54 changes: 54 additions & 0 deletions examples/express/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
{
"name": "express-example",
"private": true,
"version": "0.1.0",
"description": "Example of Express integration with OpenTelemetry",
"scripts": {
"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 .",
"setup": "cd ../../../../ && npm ci && cd plugins/node/opentelemetry-instrumentation-express && npm run compile && cd examples && npm run compile"
},
"repository": {
"type": "git",
"url": "git+ssh://[email protected]/open-telemetry/opentelemetry-js-contrib.git",
"directory": "plugins/node/opentelemetry-instrumentation-express"
},
"keywords": [
"opentelemetry",
"express",
"tracing"
],
"engines": {
"node": ">=14"
},
"author": "OpenTelemetry Authors",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/open-telemetry/opentelemetry-js-contrib/issues"
},
"homepage": "https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/plugins/node/opentelemetry-instrumentation-express/examples#readme",
"dependencies": {
"@opentelemetry/api": "^1.3.0",
"@opentelemetry/exporter-jaeger": "^1.18.1",
"@opentelemetry/exporter-trace-otlp-proto": "^0.48.0",
"@opentelemetry/exporter-zipkin": "^1.18.1",
"@opentelemetry/instrumentation": "^0.48.0",
"@opentelemetry/instrumentation-express": "^0.34.1",
"@opentelemetry/instrumentation-http": "^0.48.0",
"@opentelemetry/resources": "^1.18.1",
"@opentelemetry/sdk-trace-base": "^1.18.1",
"@opentelemetry/sdk-trace-node": "^1.18.1",
"@opentelemetry/semantic-conventions": "^1.18.1",
"axios": "^1.6.0",
"cross-env": "^7.0.3",
"express": "^4.17.1"
},
"devDependencies": {
"@types/express": "^4.17.13",
"ts-node": "^10.6.0",
"typescript": "4.4.4"
}
}
32 changes: 32 additions & 0 deletions examples/express/src/client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
'use strict';

// eslint-disable-next-line import/order
import { setupTracing } from "./tracer";
const tracer = setupTracing('example-express-client');

import * as api from '@opentelemetry/api';
import { default as axios } from 'axios';

function makeRequest() {
const span = tracer.startSpan('client.makeRequest()', {
kind: api.SpanKind.CLIENT,
});

api.context.with(api.trace.setSpan(api.ROOT_CONTEXT, span), async () => {
try {
const res = await axios.get('http://localhost:8080/run_test');
console.log('status:', res.statusText);
span.setStatus({ code: api.SpanStatusCode.OK });
} catch (e) {
if (e instanceof Error) {
console.log('failed:', e.message);
span.setStatus({ code: api.SpanStatusCode.ERROR, message: e.message });
}
}
span.end();
console.log('Sleeping 5 seconds before shutdown to ensure all records are flushed.');
setTimeout(() => { console.log('Completed.'); }, 5000);
});
}

makeRequest();
55 changes: 55 additions & 0 deletions examples/express/src/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { setupTracing } from './tracer'

setupTracing('example-express-server');

// Require in rest of modules
import * as express from 'express';
import { default as axios } from 'axios';
import { RequestHandler } from "express";

// Setup express
const app = express();
const PORT = 8080;

const getCrudController = () => {
const router = express.Router();
const resources: any[] = [];
router.get('/', (req, res) => res.send(resources));
router.post('/', (req, res) => {
resources.push(req.body);
return res.status(201).send(req.body);
});
return router;
};

const authMiddleware: RequestHandler = (req, res, next) => {
const { authorization } = req.headers;
if (authorization && authorization.includes('secret_token')) {
next();
} else {
res.sendStatus(401);
}
};

app.use(express.json());
app.get('/health', (req, res) => res.status(200).send("HEALTHY")); // endpoint that is called by framework/cluster
app.get('/run_test', async (req, res) => {
// Calls another endpoint of the same API, somewhat mimicing an external API call
const createdCat = await axios.post(`http://localhost:${PORT}/cats`, {
name: 'Tom',
friends: [
'Jerry',
],
}, {
headers: {
Authorization: 'secret_token',
},
});

return res.status(201).send(createdCat.data);
});
app.use('/cats', authMiddleware, getCrudController());

app.listen(PORT, () => {
console.log(`Listening on http://localhost:${PORT}`);
});
69 changes: 69 additions & 0 deletions examples/express/src/tracer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
'use strict';

import { SpanKind, Attributes } from "@opentelemetry/api";

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

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

import { registerInstrumentations } from '@opentelemetry/instrumentation';
import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
import { Sampler, AlwaysOnSampler, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto';
import { ZipkinExporter } from '@opentelemetry/exporter-zipkin';
import { Resource } from '@opentelemetry/resources';
import { SemanticAttributes, SemanticResourceAttributes as ResourceAttributesSC } from '@opentelemetry/semantic-conventions';

const Exporter = (process.env.EXPORTER || '').toLowerCase().startsWith('z') ? ZipkinExporter : OTLPTraceExporter;
import { ExpressInstrumentation } from '@opentelemetry/instrumentation-express';
const { HttpInstrumentation } = require('@opentelemetry/instrumentation-http');

export const setupTracing = (serviceName: string) => {
const provider = new NodeTracerProvider({
resource: new Resource({
[ResourceAttributesSC.SERVICE_NAME]: serviceName,
}),
sampler: filterSampler(ignoreHealthCheck, new AlwaysOnSampler()),
});
registerInstrumentations({
tracerProvider: provider,
instrumentations: [
// Express instrumentation expects HTTP layer to be instrumented
HttpInstrumentation,
ExpressInstrumentation,
],
});

const exporter = new Exporter({
serviceName,
});

provider.addSpanProcessor(new SimpleSpanProcessor(exporter));

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

return opentelemetry.trace.getTracer(serviceName);
};

type FilterFunction = (spanName: string, spanKind: SpanKind, attributes: Attributes) => boolean;

function filterSampler(filterFn: FilterFunction, parent: Sampler): Sampler {
return {
shouldSample(ctx, tid, spanName, spanKind, attr, links) {
if (!filterFn(spanName, spanKind, attr)) {
return { decision: opentelemetry.SamplingDecision.NOT_RECORD };
}
return parent.shouldSample(ctx, tid, spanName, spanKind, attr, links);
},
toString() {
return `FilterSampler(${parent.toString()})`;
}
}
}

function ignoreHealthCheck(spanName: string, spanKind: SpanKind, attributes: Attributes) {
return spanKind !== opentelemetry.SpanKind.SERVER || attributes[SemanticAttributes.HTTP_ROUTE] !== "/health";
}
10 changes: 10 additions & 0 deletions examples/express/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"noEmit": true,
"rootDir": ".",
},
"include": [
"src/**/*.ts",
]
}

0 comments on commit 0cc9047

Please sign in to comment.