Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: moves express examples into its package to establish pattern #939

Merged
merged 23 commits into from
May 3, 2022
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
07d84ad
chore: moves express examples into its package to establish pattern
andyfleming Mar 9, 2022
e8b191e
Merge branch 'main' into start-examples-reorg
andyfleming Mar 16, 2022
9d01290
revert: unintentional path change
andyfleming Mar 16, 2022
a1ce105
fix: uses more correct value
andyfleming Mar 16, 2022
c7d1a64
chore: bumps dependency versions
andyfleming Mar 16, 2022
4816bb3
Adds instructions for migrating examples
andyfleming Mar 16, 2022
5daa9fc
Update plugins/node/opentelemetry-instrumentation-express/examples/pa…
andyfleming Mar 18, 2022
93868d0
Update plugins/node/opentelemetry-instrumentation-express/examples/pa…
andyfleming Mar 18, 2022
7c723cb
ignores examples from lint
andyfleming Mar 22, 2022
b89a026
Merge remote-tracking branch 'upstream/main' into start-examples-reorg
andyfleming Mar 22, 2022
b7417c4
removes extra line
andyfleming Mar 22, 2022
7d8390b
bumps otel dependency versions
andyfleming Mar 23, 2022
0514cf6
cleanup
andyfleming Mar 23, 2022
3b362ed
updates to use package name instead of relative path
andyfleming Mar 24, 2022
5fd98d1
updates CI approach to use lerna run command
andyfleming Mar 24, 2022
c4fe55c
Merge branch 'main' into start-examples-reorg
rauno56 Apr 4, 2022
934daeb
Merge branch 'main' into start-examples-reorg
rauno56 Apr 4, 2022
3205251
bumps dependency versions
andyfleming Apr 12, 2022
8f12561
Merge branch 'main' into start-examples-reorg
Flarna Apr 13, 2022
94a73fa
Merge branch 'main' into start-examples-reorg
rauno56 Apr 18, 2022
55551a6
Merge branch 'main' into start-examples-reorg
andyfleming Apr 20, 2022
cd3f077
Merge branch 'main' into start-examples-reorg
rauno56 Apr 26, 2022
891f621
Merge branch 'main' into start-examples-reorg
rauno56 May 3, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/unit-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,8 @@ jobs:
run: npx lerna bootstrap --no-ci
- name: Unit tests
run: npm run test:browser
- name: Build examples
run: npm run --if-present compile:examples
andyfleming marked this conversation as resolved.
Show resolved Hide resolved
- name: Report Coverage
uses: codecov/codecov-action@v2
with:
Expand Down
42 changes: 42 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Instrumentation Examples

:warning: Note: We are working on migrating these examples to their respective package directories.

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).


## Instructions for Migrating an Example

* [ ] 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 `package.json` in the examples folder
* [ ] Remove the `@opentelemetry/instrumentation-[name]` dependency.
* [ ] Install `typescript` and `ts-node` in the examples directory.
* [ ] Replace usage of `node` in scripts with `ts-node`.
* [ ] Add a script for compiling the code in scripts: `"compile": "tsc -p ."`
* [ ] Add a tsconfig.json file in the examples folder. (Example below)
* [ ] Update the code
* [ ] Change code to use a relative import of the library.
* [ ] Add types to the code
* [ ] Update the instrumentation package's `package.json`
* [ ] Add a script `"compile:examples": "cd examples && npm run compile",`.
* [ ] Test the updated code
* [ ] Test building the examples by running `npm run compile:examples`
* [ ] Test that the actual exapmle code runs as expected

Example tsconfig.json file:

```json
{
"extends": "../tsconfig.json",
"compilerOptions": {
"noEmit": true,
"rootDir": ".",
},
"include": [
"src/**/*.ts",
"test/**/*.ts"
blumamir marked this conversation as resolved.
Show resolved Hide resolved
]
}
```
47 changes: 0 additions & 47 deletions examples/express/package.json

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
{
"name": "express-example",
"private": true,
"version": "0.28.0",
"description": "Example of Express integration with OpenTelemetry",
"main": "index.js",
"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 ."
},
"repository": {
"type": "git",
"url": "git+ssh://[email protected]/open-telemetry/opentelemetry-js.git"
},
"keywords": [
"opentelemetry",
"express",
"tracing"
],
"engines": {
"node": ">=8"
},
"author": "OpenTelemetry Authors",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/open-telemetry/opentelemetry-js/issues"
},
"dependencies": {
"@opentelemetry/api": "^1.0.2",
"@opentelemetry/exporter-jaeger": "^0.26.0",
"@opentelemetry/exporter-zipkin": "^0.26.0",
"@opentelemetry/instrumentation": "^0.27.0",
"@opentelemetry/instrumentation-http": "^0.27.0",
"@opentelemetry/resources": "^0.26.0",
"@opentelemetry/sdk-trace-base": "^1.0.0",
"@opentelemetry/sdk-trace-node": "^0.26.0",
andyfleming marked this conversation as resolved.
Show resolved Hide resolved
"@opentelemetry/semantic-conventions": "^0.26.0",
"axios": "^0.21.1",
"cross-env": "^7.0.3",
"express": "^4.17.1"
blumamir marked this conversation as resolved.
Show resolved Hide resolved
},
"homepage": "https://github.com/open-telemetry/opentelemetry-js#readme",
"devDependencies": {
"ts-node": "^10.6.0",
"typescript": "^4.6.2"
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
'use strict';

// eslint-disable-next-line import/order
const tracer = require('./tracer')('example-express-client');
const api = require('@opentelemetry/api');
const axios = require('axios').default;
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()', {
Expand All @@ -16,8 +18,10 @@ function makeRequest() {
console.log('status:', res.statusText);
span.setStatus({ code: api.SpanStatusCode.OK });
} catch (e) {
console.log('failed:', e.message);
span.setStatus({ code: api.SpanStatusCode.ERROR, message: e.message });
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.');
Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
'use strict';
import { setupTracing } from './tracer'

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

// Require in rest of modules
const express = require('express');
const axios = require('axios').default;
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 = [];
const resources: any[] = [];
router.get('/', (req, res) => res.send(resources));
router.post('/', (req, res) => {
resources.push(req.body);
Expand All @@ -22,7 +22,7 @@ const getCrudController = () => {
return router;
};

const authMiddleware = (req, res, next) => {
const authMiddleware: RequestHandler = (req, res, next) => {
const { authorization } = req.headers;
if (authorization && authorization.includes('secret_token')) {
next();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,26 +1,28 @@
'use strict';

import { Sampler, SpanKind } 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);

const { AlwaysOnSampler } = require('@opentelemetry/core');
const { registerInstrumentations } = require('@opentelemetry/instrumentation');
const { NodeTracerProvider } = require('@opentelemetry/sdk-trace-node');
const { SimpleSpanProcessor } = require('@opentelemetry/sdk-trace-base');
const { JaegerExporter } = require('@opentelemetry/exporter-jaeger');
const { ZipkinExporter } = require('@opentelemetry/exporter-zipkin');
const { Resource } = require('@opentelemetry/resources');
const { SemanticAttributes, SemanticResourceAttributes: ResourceAttributesSC } = require('@opentelemetry/semantic-conventions');
import { AlwaysOnSampler } from '@opentelemetry/core';
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 { SemanticAttributes, SemanticResourceAttributes as ResourceAttributesSC } from '@opentelemetry/semantic-conventions';
import { SpanAttributes } from "@opentelemetry/api/build/src/trace/attributes";

const Exporter = (process.env.EXPORTER || '')
.toLowerCase().startsWith('z') ? ZipkinExporter : JaegerExporter;
const { ExpressInstrumentation } = require('@opentelemetry/instrumentation-express');
const Exporter = (process.env.EXPORTER || '').toLowerCase().startsWith('z') ? ZipkinExporter : JaegerExporter;
const { ExpressInstrumentation } = require('../../src');
andyfleming marked this conversation as resolved.
Show resolved Hide resolved
const { HttpInstrumentation } = require('@opentelemetry/instrumentation-http');

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

return opentelemetry.trace.getTracer('express-example');
return opentelemetry.trace.getTracer(serviceName);
};

function filterSampler(filterFn, parent) {
type FilterFunction = (spanName: string, spanKind: SpanKind, attributes: SpanAttributes) => boolean;

function filterSampler(filterFn: FilterFunction, parent: Sampler): Sampler {
return {
shouldSample(ctx, tid, spanName, spanKind, attr, links) {
if (!filterFn(spanName, spanKind, attr)) {
Expand All @@ -62,6 +66,6 @@ function filterSampler(filterFn, parent) {
}
}

function ignoreHealthCheck(spanName, spanKind, attributes) {
function ignoreHealthCheck(spanName: string, spanKind: SpanKind, attributes: SpanAttributes) {
return spanKind !== opentelemetry.SpanKind.SERVER || attributes[SemanticAttributes.HTTP_ROUTE] !== "/health";
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"noEmit": true,
"rootDir": ".",
},
"include": [
"src/**/*.ts",
"test/**/*.ts"
blumamir marked this conversation as resolved.
Show resolved Hide resolved
]
}
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