chore: update and fix tracer-web examples (#2661)

This commit is contained in:
Nev 2021-12-15 08:05:40 -08:00 committed by GitHub
parent f59c5b268b
commit 10cd9163a0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 425 additions and 32 deletions

View File

@ -1,6 +1,6 @@
{
"env": {
"node": true
"browser": true
},
"extends": "airbnb-base",
"parserOptions": {
@ -11,6 +11,7 @@
"no-use-before-define": ["error", "nofunc"],
"no-console": "off",
"import/no-unresolved": "off",
"no-unused-vars": ["error", { "argsIgnorePattern": "^_" }]
"no-unused-vars": ["error", { "argsIgnorePattern": "^_" }],
"import/no-extraneous-dependencies": [ "error", { "devDependencies": true } ]
}
}

View File

@ -18,10 +18,33 @@ npm start
By default, the application will run on port `8090`.
Other options for running the application, this serves the same examples using different source file processing so you can review the different effects on the resulting bundle sizes that are loaded via the browser.
| Command | Description
|---------|------------
| `npm start` (Default) | Serve the raw development bundles compressed via GZip
| `npm run start-nc` | Serve the raw development bundles uncompressed
| `npm run start-prod` | Serve the minified production bundles compressed via GZip
| `npm run start-prodnc` | Serve the minified production bundles uncompressed
The development modes includes source maps via the webpack devtool `eval-source-map` mode which substantially increases the size of the bundles.
## Examples
The examples includes several variants so that you can see how to mix and match individual components and the impact this can have on the resulting bundle size.
### XMLHttpRequest
This example shows how to use the XMLHttpRequest Instrumentation with the OTLP Trace exporter and with the B3 Propagator.
Included Components
- XMLHttpRequestInstrumentation
- ZoneContextManager
- OTLPTraceExporter
- WebTracerProvider
- B3Propagator
To see the results, open the browser at <http://localhost:8090/xml-http-request/> and make sure you have the browser console open. The application is using the `ConsoleSpanExporter` and will post the created spans to the browser console.
The screen will look as follows:
@ -29,8 +52,63 @@ The screen will look as follows:
### Fetch
This example shows how to use the Fetch Instrumentation with the OTLP Trace exporter and with the B3 Propagator.
Included Components
- FetchInstrumentation
- ZoneContextManager
- OTLPTraceExporter
- WebTracerProvider
- B3Propagator
To see the results, open the browser at <http://localhost:8090/fetch/> and make sure you have the browser console open. The application is using the `ConsoleSpanExporter` and will post the created spans to the browser console.
### FetchXhr
This example shows how to use both the XMLHttpRequest and Fetch Instrumentations with the OTLP Trace exporter but without the B3 Propagator.
Included Components
- XMLHttpRequestInstrumentation
- FetchInstrumentation
- ZoneContextManager
- OTLPTraceExporter
- WebTracerProvider
### FetchXhrB3
This example shows how to use both the XMLHttpRequest and Fetch Instrumentations with the OTLP Trace exporter and with the B3 Propagator
Included Components
- XMLHttpRequestInstrumentation
- FetchInstrumentation
- ZoneContextManager
- OTLPTraceExporter
- WebTracerProvider
- B3Propagator
### Metrics
This example shows how to use the OTLP Metric Exporter, it does not include the Trace Exporter. Does not include traces
Included Components
- OTLPMetricExporter
- MeterProvider
- Resource
- SemanticResourceAttributes
### Zipkin
This example show a simple usage of the ZipKin Exporter with the Web Tracer Provider
Included Components
- WebTracerProvider
- ZipkinExporter
## Useful links
- For more information on OpenTelemetry, visit: <https://opentelemetry.io/>

View File

@ -1,7 +1,6 @@
'use strict';
import { context, trace } from '@opentelemetry/api';
import { ConsoleSpanExporter, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';
import { OTLPTraceExporter } from '@opentelemetry/exporter-otlp-http';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { WebTracerProvider } from '@opentelemetry/sdk-trace-web';
import { FetchInstrumentation } from '@opentelemetry/instrumentation-fetch';
import { ZoneContextManager } from '@opentelemetry/context-zone';
@ -9,6 +8,10 @@ import { B3Propagator } from '@opentelemetry/propagator-b3';
import { registerInstrumentations } from '@opentelemetry/instrumentation';
const provider = new WebTracerProvider();
// Note: For production consider using the "BatchSpanProcessor" to reduce the number of requests
// to your exporter. Using the SimpleSpanProcessor here as it sends the spans immediately to the
// exporter without delay
provider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter()));
provider.addSpanProcessor(new SimpleSpanProcessor(new OTLPTraceExporter()));
provider.register({
@ -34,7 +37,7 @@ const webTracerWithZone = provider.getTracer('example-tracer-web');
const getData = (url) => fetch(url, {
method: 'GET',
headers: {
'Accept': 'application/json',
Accept: 'application/json',
'Content-Type': 'application/json',
},
});
@ -46,7 +49,7 @@ const prepareClickEvent = () => {
const element = document.getElementById('button1');
const onClick = () => {
const singleSpan = webTracerWithZone.startSpan(`files-series-info`);
const singleSpan = webTracerWithZone.startSpan('files-series-info');
context.with(trace.setSpan(context.active(), singleSpan), () => {
getData(url).then((_data) => {
trace.getSpan(context.active()).addEvent('fetching-single-span-completed');

View File

@ -0,0 +1,20 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Fetch Plugin Example</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
Example of using Web Tracer with Fetch and XMLHttpRequest plugins with console exporter and collector exporter without the B3 Propagator
<script type="text/javascript" src="fetchXhr.js"></script>
<br/>
<button id="button1">Fetch Test</button>
<button id="button2">Xhr Test</button>
</body>
</html>

View File

@ -0,0 +1,93 @@
import { context, trace } from '@opentelemetry/api';
import { ConsoleSpanExporter, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { WebTracerProvider } from '@opentelemetry/sdk-trace-web';
import { FetchInstrumentation } from '@opentelemetry/instrumentation-fetch';
import { XMLHttpRequestInstrumentation } from '@opentelemetry/instrumentation-xml-http-request';
import { ZoneContextManager } from '@opentelemetry/context-zone';
import { registerInstrumentations } from '@opentelemetry/instrumentation';
const provider = new WebTracerProvider();
// Note: For production consider using the "BatchSpanProcessor" to reduce the number of requests
// to your exporter. Using the SimpleSpanProcessor here as it sends the spans immediately to the
// exporter without delay
provider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter()));
provider.addSpanProcessor(new SimpleSpanProcessor(new OTLPTraceExporter()));
provider.register({
contextManager: new ZoneContextManager(),
});
registerInstrumentations({
instrumentations: [
new FetchInstrumentation({
ignoreUrls: [/localhost:8090\/sockjs-node/],
propagateTraceHeaderCorsUrls: [
'https://cors-test.appspot.com/test',
'https://httpbin.org/get',
],
clearTimingResources: true,
}),
new XMLHttpRequestInstrumentation({
ignoreUrls: [/localhost:8090\/sockjs-node/],
propagateTraceHeaderCorsUrls: [
'https://httpbin.org/get',
],
}),
],
});
const webTracerWithZone = provider.getTracer('example-tracer-web');
const getData = (url) => fetch(url, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
});
const getDataXhr = (url) => new Promise((resolve, reject) => {
const req = new XMLHttpRequest();
req.open('GET', url, true);
req.setRequestHeader('Content-Type', 'application/json');
req.setRequestHeader('Accept', 'application/json');
req.onload = () => {
resolve();
};
req.onerror = () => {
reject();
};
req.send();
});
// example of keeping track of context between async operations
const prepareClickEvent = () => {
const url = 'https://httpbin.org/get';
const element1 = document.getElementById('button1');
const element2 = document.getElementById('button2');
const clickHandler = (fetchFn) => () => {
const singleSpan = webTracerWithZone.startSpan('files-series-info');
context.with(trace.setSpan(context.active(), singleSpan), () => {
fetchFn(url).then((_data) => {
trace.getSpan(context.active()).addEvent('fetching-single-span-completed');
singleSpan.end();
});
});
for (let i = 0, j = 5; i < j; i += 1) {
const span = webTracerWithZone.startSpan(`files-series-info-${i}`);
context.with(trace.setSpan(context.active(), span), () => {
fetchFn(url).then((_data) => {
trace.getSpan(context.active()).addEvent(`fetching-span-${i}-completed`);
span.end();
});
});
}
};
element1.addEventListener('click', clickHandler(getData));
element2.addEventListener('click', clickHandler(getDataXhr));
};
window.addEventListener('load', prepareClickEvent);

View File

@ -0,0 +1,20 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Fetch Plugin Example</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
Example of using Web Tracer with Fetch and XMLHttpRequest plugins with console exporter and collector exporter with B3 Propagator
<script type="text/javascript" src="fetchXhr.js"></script>
<br/>
<button id="button1">Fetch Test</button>
<button id="button2">Xhr Test</button>
</body>
</html>

View File

@ -0,0 +1,95 @@
import { context, trace } from '@opentelemetry/api';
import { ConsoleSpanExporter, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { WebTracerProvider } from '@opentelemetry/sdk-trace-web';
import { FetchInstrumentation } from '@opentelemetry/instrumentation-fetch';
import { XMLHttpRequestInstrumentation } from '@opentelemetry/instrumentation-xml-http-request';
import { ZoneContextManager } from '@opentelemetry/context-zone';
import { B3Propagator } from '@opentelemetry/propagator-b3';
import { registerInstrumentations } from '@opentelemetry/instrumentation';
const provider = new WebTracerProvider();
// Note: For production consider using the "BatchSpanProcessor" to reduce the number of requests
// to your exporter. Using the SimpleSpanProcessor here as it sends the spans immediately to the
// exporter without delay
provider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter()));
provider.addSpanProcessor(new SimpleSpanProcessor(new OTLPTraceExporter()));
provider.register({
contextManager: new ZoneContextManager(),
propagator: new B3Propagator(),
});
registerInstrumentations({
instrumentations: [
new FetchInstrumentation({
ignoreUrls: [/localhost:8090\/sockjs-node/],
propagateTraceHeaderCorsUrls: [
'https://cors-test.appspot.com/test',
'https://httpbin.org/get',
],
clearTimingResources: true,
}),
new XMLHttpRequestInstrumentation({
ignoreUrls: [/localhost:8090\/sockjs-node/],
propagateTraceHeaderCorsUrls: [
'https://httpbin.org/get',
],
}),
],
});
const webTracerWithZone = provider.getTracer('example-tracer-web');
const getData = (url) => fetch(url, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
});
const getDataXhr = (url) => new Promise((resolve, reject) => {
const req = new XMLHttpRequest();
req.open('GET', url, true);
req.setRequestHeader('Content-Type', 'application/json');
req.setRequestHeader('Accept', 'application/json');
req.onload = () => {
resolve();
};
req.onerror = () => {
reject();
};
req.send();
});
// example of keeping track of context between async operations
const prepareClickEvent = () => {
const url = 'https://httpbin.org/get';
const element1 = document.getElementById('button1');
const element2 = document.getElementById('button2');
const clickHandler = (fetchFn) => () => {
const singleSpan = webTracerWithZone.startSpan('files-series-info');
context.with(trace.setSpan(context.active(), singleSpan), () => {
fetchFn(url).then((_data) => {
trace.getSpan(context.active()).addEvent('fetching-single-span-completed');
singleSpan.end();
});
});
for (let i = 0, j = 5; i < j; i += 1) {
const span = webTracerWithZone.startSpan(`files-series-info-${i}`);
context.with(trace.setSpan(context.active(), span), () => {
fetchFn(url).then((_data) => {
trace.getSpan(context.active()).addEvent(`fetching-span-${i}-completed`);
span.end();
});
});
}
};
element1.addEventListener('click', clickHandler(getData));
element2.addEventListener('click', clickHandler(getDataXhr));
};
window.addEventListener('load', prepareClickEvent);

View File

@ -1,7 +1,5 @@
'use strict';
const { DiagConsoleLogger, DiagLogLevel, diag } = require('@opentelemetry/api');
const { OTLPMetricExporter } = require('@opentelemetry/exporter-otlp-http');
const { OTLPMetricExporter } = require('@opentelemetry/exporter-metrics-otlp-http');
const { MeterProvider } = require('@opentelemetry/sdk-metrics-base');
const { Resource } = require('@opentelemetry/resources');
const { SemanticResourceAttributes } = require('@opentelemetry/semantic-conventions');
@ -48,6 +46,7 @@ function startMetrics() {
const addClickEvents = () => {
const startBtn = document.getElementById('startBtn');
const stopBtn = document.getElementById('stopBtn');
startBtn.addEventListener('click', startMetrics);
stopBtn.addEventListener('click', stopMetrics);

View File

@ -3,11 +3,15 @@ import { ConsoleSpanExporter, SimpleSpanProcessor } from '@opentelemetry/sdk-tra
import { WebTracerProvider } from '@opentelemetry/sdk-trace-web';
import { XMLHttpRequestInstrumentation } from '@opentelemetry/instrumentation-xml-http-request';
import { ZoneContextManager } from '@opentelemetry/context-zone';
import { OTLPTraceExporter } from '@opentelemetry/exporter-otlp-http';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { B3Propagator } from '@opentelemetry/propagator-b3';
import { registerInstrumentations } from '@opentelemetry/instrumentation';
const providerWithZone = new WebTracerProvider();
// Note: For production consider using the "BatchSpanProcessor" to reduce the number of requests
// to your exporter. Using the SimpleSpanProcessor here as it sends the spans immediately to the
// exporter without delay
providerWithZone.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter()));
providerWithZone.addSpanProcessor(new SimpleSpanProcessor(new OTLPTraceExporter()));
@ -30,7 +34,6 @@ registerInstrumentations({
const webTracerWithZone = providerWithZone.getTracer('example-tracer-web');
const getData = (url) => new Promise((resolve, reject) => {
// eslint-disable-next-line no-undef
const req = new XMLHttpRequest();
req.open('GET', url, true);
req.setRequestHeader('Content-Type', 'application/json');
@ -57,7 +60,7 @@ const prepareClickEvent = () => {
getData(url1).then((_data) => {
trace.getSpan(context.active()).addEvent('fetching-span1-completed');
span1.end();
}, ()=> {
}, () => {
trace.getSpan(context.active()).addEvent('fetching-error');
span1.end();
});

View File

@ -1,11 +1,14 @@
{
"name": "web-tracer-example",
"private": true,
"version": "0.25.0",
"version": "0.27.0",
"description": "Example of using @opentelemetry/sdk-trace-web in browser",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server -d --progress --colors --port 8090 --config webpack.config.js --hot --inline --host 0.0.0.0 --content-base examples"
"start": "webpack serve --progress --color --port 8090 --config webpack.dev.config.js --hot --host 0.0.0.0 --compress",
"start-nc": "webpack serve --progress --color --port 8090 --config webpack.dev.config.js --hot --host 0.0.0.0 --no-compress",
"start-prod": "webpack serve --progress --color --port 8090 --config webpack.prod.config.js --hot --host 0.0.0.0 --compress",
"start-prodnc": "webpack serve --progress --color --port 8090 --config webpack.prod.config.js --hot --host 0.0.0.0 --no-compress"
},
"repository": {
"type": "git",
@ -27,25 +30,29 @@
"devDependencies": {
"@babel/core": "^7.6.0",
"babel-loader": "^8.0.6",
"ts-loader": "^6.0.4",
"webpack": "^4.35.2",
"webpack-cli": "^3.3.9",
"webpack-dev-server": "^3.8.1",
"webpack-merge": "^4.2.2"
"ts-loader": "^9.2.6",
"typescript": "^4.5.2",
"webpack": "^5.65.0",
"webpack-cli": "^4.9.1",
"webpack-dev-server": "^4.6.0",
"webpack-merge": "^5.8.0"
},
"dependencies": {
"@opentelemetry/api": "^1.0.2",
"@opentelemetry/context-zone": "0.25.0",
"@opentelemetry/core": "0.25.0",
"@opentelemetry/exporter-otlp-http": "0.25.0",
"@opentelemetry/exporter-zipkin": "0.25.0",
"@opentelemetry/instrumentation": "0.25.0",
"@opentelemetry/instrumentation-fetch": "0.25.0",
"@opentelemetry/instrumentation-xml-http-request": "0.25.0",
"@opentelemetry/sdk-metrics-base": "0.25.0",
"@opentelemetry/propagator-b3": "0.25.0",
"@opentelemetry/sdk-trace-base": "0.25.0",
"@opentelemetry/sdk-trace-web": "0.25.0"
"@opentelemetry/context-zone": "^1.0.1",
"@opentelemetry/core": "^1.0.1",
"@opentelemetry/sdk-trace-base": "^1.0.1",
"@opentelemetry/sdk-trace-web": "^1.0.1",
"@opentelemetry/exporter-zipkin": "^1.0.1",
"@opentelemetry/semantic-conventions": "^1.0.1",
"@opentelemetry/propagator-b3": "^1.0.1",
"@opentelemetry/resources": "^1.0.1",
"@opentelemetry/instrumentation": "0.27.0",
"@opentelemetry/instrumentation-fetch": "0.27.0",
"@opentelemetry/instrumentation-xml-http-request": "0.27.0",
"@opentelemetry/exporter-trace-otlp-http": "0.27.0",
"@opentelemetry/exporter-metrics-otlp-http": "0.27.0",
"@opentelemetry/sdk-metrics-base": "0.27.0"
},
"homepage": "https://github.com/open-telemetry/opentelemetry-js#readme"
}

View File

@ -10,6 +10,8 @@ const common = {
metrics: 'examples/metrics/index.js',
fetch: 'examples/fetch/index.js',
'xml-http-request': 'examples/xml-http-request/index.js',
fetchXhr: 'examples/fetchXhr/index.js',
fetchXhrB3: 'examples/fetchXhrB3/index.js',
zipkin: 'examples/zipkin/index.js',
},
output: {
@ -43,12 +45,18 @@ const common = {
],
extensions: ['.ts', '.js', '.jsx', '.json'],
},
optimization: {
minimize: false,
},
};
module.exports = webpackMerge(common, {
module.exports = webpackMerge.merge(common, {
devtool: 'eval-source-map',
devServer: {
contentBase: path.resolve(__dirname),
static: {
directory: path.resolve(__dirname, 'examples'),
},
compress: true,
},
plugins: [
new webpack.DefinePlugin({

View File

@ -0,0 +1,66 @@
const webpack = require('webpack');
const webpackMerge = require('webpack-merge');
const path = require('path');
const directory = path.resolve(__dirname);
const common = {
mode: 'production',
entry: {
metrics: 'examples/metrics/index.js',
fetch: 'examples/fetch/index.js',
'xml-http-request': 'examples/xml-http-request/index.js',
fetchXhr: 'examples/fetchXhr/index.js',
fetchXhrB3: 'examples/fetchXhrB3/index.js',
zipkin: 'examples/zipkin/index.js',
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
sourceMapFilename: '[file].map',
},
target: 'web',
module: {
rules: [
{
test: /\.js[x]?$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
},
},
{
test: /\.ts$/,
exclude: /(node_modules)/,
use: {
loader: 'ts-loader',
},
},
],
},
resolve: {
modules: [
path.resolve(directory),
'node_modules',
],
extensions: ['.ts', '.js', '.jsx', '.json'],
},
optimization: {
minimize: true,
},
};
module.exports = webpackMerge.merge(common, {
devtool: 'source-map',
devServer: {
static: {
directory: path.resolve(__dirname, 'examples'),
},
compress: true,
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production'),
}),
],
});