Skip to content

Commit

Permalink
chore(opencensus-shim) add example code
Browse files Browse the repository at this point in the history
  • Loading branch information
aabmass committed May 17, 2023
1 parent 76383d0 commit b55e74a
Show file tree
Hide file tree
Showing 7 changed files with 293 additions and 0 deletions.
84 changes: 84 additions & 0 deletions experimental/examples/opencensus-shim/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
# Overview

OpenTracing shim allows existing OpenTracing instrumentation to report to OpenTelemetry.

This is a simple example that demonstrates how existing OpenTracing instrumentation can be integrated with OpenTelemetry.

The example shows key aspects of tracing such as

- Root Span (on client)
- Child Span from a remote parent (on server)
- Span Tag
- Span Log
- Make a shim between OpenTracing and OpenTelemetry tracers

## Installation

```sh
# from this directory
$ npm install
```

## Run the Application

### Zipkin

- Setup [Zipkin Tracing UI](https://zipkin.io/pages/quickstart.html)

- Run the server

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

- Run the client

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

- Check trace

`zipkin:client` should output the `traceId` in the terminal.

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-ui.png?raw=true"/></p>

### Jaeger

- Setup [Jaeger Tracing UI](https://www.jaegertracing.io/docs/latest/getting-started/#all-in-one)

- Run the server

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

- Run the client

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

- Check trace

`jaeger:client` should output the `traceId` in the terminal.

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-ui.png?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>
- For more information on OpenTracing, visit: <https://opentracing.io/>

## LICENSE

Apache License 2.0
54 changes: 54 additions & 0 deletions experimental/examples/opencensus-shim/client.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';

const setup = require('./setup');

const provider = setup('opencensus-shim-example-client');

const http = require('http');

makeRequest();

async function makeRequest() {
const data = await new Promise((resolve, reject) => {
http
.get(
{
host: 'localhost',
port: 3000,
path: '/',
},
resp => {
let data = '';

resp.on('data', chunk => {
data += chunk;
});

resp.on('end', async () => {
resolve(JSON.parse(data));
});
}
)
.on('error', err => {
reject(err);
});
});
console.log('Got data from server: ', data);

await provider.shutdown();
}
41 changes: 41 additions & 0 deletions experimental/examples/opencensus-shim/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"name": "opencensus-shim",
"private": true,
"version": "0.38.0",
"description": "Example of using @opentelemetry/shim-opencensus in Node.js",
"main": "index.js",
"scripts": {
"client": "node -r @opentelemetry/shim-opencensus/register ./client.js",
"server": "node -r @opentelemetry/shim-opencensus/register ./server.js"
},
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/open-telemetry/opentelemetry-js.git"
},
"keywords": [
"opentelemetry",
"http",
"tracing",
"opencensus"
],
"engines": {
"node": ">=14"
},
"author": "OpenTelemetry Authors",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/open-telemetry/opentelemetry-js/issues"
},
"dependencies": {
"@opentelemetry/api": "1.4.1",
"@opentelemetry/sdk-trace-node": "1.12.0",
"@opencensus/core": "0.1.0",
"@opencensus/nodejs": "0.1.0",
"@opentelemetry/semantic-conventions": "1.12.0",
"@opentelemetry/exporter-jaeger": "1.12.0",
"@opentelemetry/resources": "1.12.0",
"@opentelemetry/shim-opencensus": "0.38.0"
},
"homepage": "https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/examples/opencensus-shim",
"devDependencies": {}
}
39 changes: 39 additions & 0 deletions experimental/examples/opencensus-shim/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
'use strict';

const { SpanStatusCode } = require('@opentelemetry/api');
const setup = require('./setup');
const utils = require('./utils');
const { trace } = require('@opentelemetry/api');

setup('opencensus-shim-example-server');
const http = require('http');

const otelTracer = trace.getTracer('opencensus-shim-example');

function startServer(port) {
// requests are traced by OpenCensus http instrumentation
const server = http.createServer(async (req, res) => {
// you can mix OTel and OC instrumentation

// deliberately sleeping to mock some action
await otelTracer.startActiveSpan('sleep', async span => {
await utils.sleep(1000);
span.end();
});

trace.getActiveSpan()?.addEvent('write headers');
res.writeHead(200, { 'Content-Type': 'application/json' });
trace.getActiveSpan()?.addEvent('write json response');
res.write(JSON.stringify({ status: 'OK', message: 'Hello World!' }));
trace.getActiveSpan()?.setStatus(SpanStatusCode.OK);
res.end();
});

server.listen(port, err => {
if (err) throw err;

console.log(`Server is listening on ${port}`);
});
}

startServer(3000);
49 changes: 49 additions & 0 deletions experimental/examples/opencensus-shim/setup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';

const { DiagConsoleLogger, diag, DiagLogLevel } = require('@opentelemetry/api');
const {
NodeTracerProvider,
BatchSpanProcessor,
} = require('@opentelemetry/sdk-trace-node');
const { JaegerExporter } = require('@opentelemetry/exporter-jaeger');
const { Resource } = require('@opentelemetry/resources');
const {
SemanticResourceAttributes,
} = require('@opentelemetry/semantic-conventions');

module.exports = function setup(serviceName) {
const tracing = require('@opencensus/nodejs');

diag.setLogger(new DiagConsoleLogger(), { logLevel: DiagLogLevel.ALL });
const provider = new NodeTracerProvider({
resource: new Resource({
[SemanticResourceAttributes.SERVICE_NAME]: serviceName,
}),
});
provider.addSpanProcessor(
new BatchSpanProcessor(new JaegerExporter(), {
scheduledDelayMillis: 5000,
})
);
provider.register();

// Start OpenCensus tracing
tracing.start({ samplingRate: 1, logger: diag });

return provider;
};
22 changes: 22 additions & 0 deletions experimental/examples/opencensus-shim/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';

async function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

exports.sleep = sleep;
4 changes: 4 additions & 0 deletions experimental/packages/shim-opencensus/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
"private": true,
"main": "build/src/index.js",
"types": "build/src/index.d.ts",
"exports": {
".": "./build/src/index.js",
"./register": "./build/src/register.js"
},
"repository": "open-telemetry/opentelemetry-js",
"scripts": {
"prepublishOnly": "npm run compile",
Expand Down

0 comments on commit b55e74a

Please sign in to comment.