Skip to content

Commit

Permalink
Merge branch 'main' into dsvanlani/update-mongodb-kebab-2528
Browse files Browse the repository at this point in the history
  • Loading branch information
trentm authored Nov 28, 2024
2 parents 6df908e + 2f5d1de commit 336b7b5
Show file tree
Hide file tree
Showing 15 changed files with 67 additions and 82 deletions.
46 changes: 18 additions & 28 deletions examples/express/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# 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.
OpenTelemetry Express Instrumentation allows the user to automatically collect trace data and export them to the backend of choice (we use 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
Expand All @@ -17,44 +17,34 @@ shows key aspects of tracing such as
npm install
```

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
npm run zipkin:server
Start Jaeger in Docker for receiving tracing data (see [the Jaeger docs](https://www.jaegertracing.io/docs/2.0/getting-started/#in-docker) for more details about running Jaeger):

```bash
docker run --rm --name jaeger \
-p 5778:5778 \
-p 16686:16686 \
-p 4317:4317 \
-p 4318:4318 \
-p 14250:14250 \
-p 14268:14268 \
-p 9411:9411 \
jaegertracing/jaeger:2.0.0 \
--set receivers.otlp.protocols.http.endpoint=0.0.0.0:4318 \
--set receivers.otlp.protocols.grpc.endpoint=0.0.0.0:4317
```

Then run the client in a separate terminal:

```sh
npm run zipkin:client
```

After a short time, the generated traces should be available in the Zipkin UI.
Visit <http://localhost:9411/zipkin> and click the "RUN QUERY" button to view
recent traces, then click "SHOW" on a given trace.

<p align="center"><img alt="Zipkin UI with trace" src="./images/zipkin.jpg?raw=true"/></p>

### Jaeger
## Run the Application

Run the server:

```sh
npm run jaeger:server
npm run server
```

Then run the client in a separate terminal:

```sh
npm run jaeger:client
npm run client
```

Visit the Jaeger UI at <http://localhost:16686/search>, select a service (e.g. "example-express-client"), click "Find Traces", then click on a trace to view it.
Expand Down
Binary file removed examples/express/images/zipkin.jpg
Binary file not shown.
26 changes: 11 additions & 15 deletions examples/express/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,8 @@
"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",
"server": "ts-node src/server.ts",
"client": "ts-node src/client.ts",
"compile": "tsc -p ."
},
"repository": {
Expand All @@ -30,23 +28,21 @@
},
"homepage": "https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/examples/express#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/api": "^1.9.0",
"@opentelemetry/exporter-trace-otlp-proto": "^0.54.2",
"@opentelemetry/instrumentation": "^0.54.2",
"@opentelemetry/instrumentation-express": "^0.44.0",
"@opentelemetry/instrumentation-http": "^0.54.2",
"@opentelemetry/resources": "^1.27.0",
"@opentelemetry/sdk-trace-base": "^1.27.0",
"@opentelemetry/sdk-trace-node": "^1.27.0",
"@opentelemetry/semantic-conventions": "^1.27.0",
"axios": "^1.6.0",
"cross-env": "^7.0.3",
"express": "^4.17.1"
},
"devDependencies": {
"@types/express": "^4.17.13",
"@types/node": "18.18.14",
"ts-node": "^10.6.0",
"typescript": "4.4.4"
}
Expand Down
32 changes: 10 additions & 22 deletions examples/express/src/tracer.ts
Original file line number Diff line number Diff line change
@@ -1,51 +1,39 @@
'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 { trace, SamplingDecision, SpanKind, Attributes } from '@opentelemetry/api';
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 { SEMRESATTRS_SERVICE_NAME, SEMATTRS_HTTP_ROUTE } from '@opentelemetry/semantic-conventions';

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

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

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

provider.addSpanProcessor(new SimpleSpanProcessor(exporter));

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

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

type FilterFunction = (spanName: string, spanKind: SpanKind, attributes: Attributes) => boolean;
Expand All @@ -54,7 +42,7 @@ 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 { decision: SamplingDecision.NOT_RECORD };
}
return parent.shouldSample(ctx, tid, spanName, spanKind, attr, links);
},
Expand All @@ -65,5 +53,5 @@ function filterSampler(filterFn: FilterFunction, parent: Sampler): Sampler {
}

function ignoreHealthCheck(spanName: string, spanKind: SpanKind, attributes: Attributes) {
return spanKind !== opentelemetry.SpanKind.SERVER || attributes[SEMATTRS_HTTP_ROUTE] !== "/health";
return spanKind !== SpanKind.SERVER || attributes[ATTR_HTTP_ROUTE] !== "/health";
}
1 change: 1 addition & 0 deletions examples/web/.npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package-lock=false
14 changes: 13 additions & 1 deletion examples/web/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,26 @@ This example shows how to use [@opentelemetry/sdk-trace-web][] with different in
npm install
```

## Start a collector and trace viewer

Optionally, you can use the provided Docker Compose file to start an OpenTelemetry Collector and a Zipkin to view collected traces.
You can skip this step if you have your own collector already setup.

```sh
npm run docker:start
```

## Run the Application

```sh
# from this directory
npm start
```

By default, the application will run on port `8090`.
- Open the application at <http://localhost:8090>.
- Click around in each of the example sub-paths to create some tracing data.
- Open Zipkin at <http://127.0.0.1:9411/zipkin/> and search for some traces (click "Run Query").


## More information

Expand Down
7 changes: 4 additions & 3 deletions examples/web/docker/collector-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ receivers:
protocols:
grpc:
http:
cors_allowed_origins:
- http://*
- https://*
cors:
allowed_origins:
- http://*
- https://*

exporters:
zipkin:
Expand Down
5 changes: 1 addition & 4 deletions examples/web/docker/docker-compose.yaml
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
version: "3"
services:
# Collector
collector:
image: otel/opentelemetry-collector:0.38.0
image: otel/opentelemetry-collector:0.99.0
command: ["--config=/conf/collector-config.yaml"]
volumes:
- ./collector-config.yaml:/conf/collector-config.yaml
Expand All @@ -13,7 +11,6 @@ services:
depends_on:
- zipkin-all-in-one

# Zipkin
zipkin-all-in-one:
image: openzipkin/zipkin:latest
ports:
Expand Down
4 changes: 2 additions & 2 deletions examples/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
"description": "Example of using web plugins in browser",
"main": "index.js",
"scripts": {
"docker:start": "cd ./docker && docker-compose down && docker-compose up",
"docker:startd": "cd ./docker && docker-compose down && docker-compose up -d",
"docker:start": "cd ./docker && docker compose down && docker compose up",
"docker:startd": "cd ./docker && docker compose down && docker compose up -d",
"start": "webpack-dev-server --progress --color --port 8090 --config ./webpack.config.js --hot --host 0.0.0.0"
},
"repository": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -392,5 +392,5 @@ function wrapPromise<T>(
}

function truncateQuery(query: unknown, maxQueryLength: number) {
return String(query).substr(0, maxQueryLength);
return String(query).substring(0, maxQueryLength);
}
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ describe('CassandraDriverInstrumentation', () => {
it('truncates long queries', async () => {
const query = 'select userid, count from ot.test';
await client.execute(query);
assertSingleSpan('cassandra-driver.execute', query.substr(0, 25));
assertSingleSpan('cassandra-driver.execute', query.substring(0, 25));
});
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ export class FastifyInstrumentation extends InstrumentationBase<FastifyInstrumen
anyRequest.routeOptions?.handler || anyRequest.context?.handler;

const handlerName = handler?.name.startsWith('bound ')
? handler.name.substr(6)
? handler.name.substring(6)
: handler?.name;
const spanName = `${FastifyNames.REQUEST_HANDLER} - ${
handlerName || this.pluginName || ANONYMOUS_NAME
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ export const limitLength = (str: string, maxLength: number) => {
0 < maxLength &&
maxLength < str.length
) {
return str.substr(0, maxLength) + '..';
return str.substring(0, maxLength) + '..';
}
return str;
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ describe('Knex instrumentation', () => {
const [span] = memoryExporter.getFinishedSpans();
const limitedStatement = span?.attributes?.['db.statement'] as string;
assert.strictEqual(limitedStatement.length, 52);
assert.ok(statement.startsWith(limitedStatement.substr(0, 50)));
assert.ok(statement.startsWith(limitedStatement.substring(0, 50)));
});

it('should catch errors', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export class OTTracePropagator implements TextMapPropagator {
const spanContext = trace.getSpan(context)?.spanContext();
if (!spanContext || !isSpanContextValid(spanContext)) return;

setter.set(carrier, OT_TRACE_ID_HEADER, spanContext.traceId.substr(16));
setter.set(carrier, OT_TRACE_ID_HEADER, spanContext.traceId.substring(16));
setter.set(carrier, OT_SPAN_ID_HEADER, spanContext.spanId);
setter.set(
carrier,
Expand Down Expand Up @@ -110,7 +110,7 @@ export class OTTracePropagator implements TextMapPropagator {
getter.keys(carrier).forEach(k => {
if (!k.startsWith(OT_BAGGAGE_PREFIX)) return;
const value = readHeader(carrier, getter, k);
baggage = baggage.setEntry(k.substr(OT_BAGGAGE_PREFIX.length), {
baggage = baggage.setEntry(k.substring(OT_BAGGAGE_PREFIX.length), {
value,
});
});
Expand Down

0 comments on commit 336b7b5

Please sign in to comment.