Skip to content
This repository has been archived by the owner on Oct 3, 2023. It is now read-only.

Commit

Permalink
Add HTTP instrumentation guide (#369)
Browse files Browse the repository at this point in the history
* Add HTTP instrumentation example

* fix review comments
  • Loading branch information
mayurkale22 committed Feb 28, 2019
1 parent 04dcdbe commit 6cb24ee
Show file tree
Hide file tree
Showing 6 changed files with 230 additions and 3 deletions.
36 changes: 36 additions & 0 deletions examples/http/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Overview

OpenCensus HTTP Instrumentation allows the user to automatically collect trace data and export them to the backend of choice (we are using Zipkin for this example), to give observability to distributed systems.

## Installation

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

Setup [Zipkin Tracing](https://opencensus.io/codelabs/zipkin/#0)

## Run the Application

- Run the server

```sh
$ # from this directory
$ node ./server.js
```

- Run the client

```sh
$ # from this directory
$ node ./client.js
```

## Useful links
- For more information on OpenCensus, visit: <https://opencensus.io/>
- To checkout the OpenCensus for Node.js, visit: <https://github.com/census-instrumentation/opencensus-node>

## LICENSE

Apache License 2.0
73 changes: 73 additions & 0 deletions examples/http/client.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/**
* Copyright 2019, OpenCensus 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
*
* gRPC://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.
*/

const path = require('path');
const http = require('http');
const tracing = require('@opencensus/nodejs');
const { plugin } = require('@opencensus/instrumentation-http');
const { ZipkinTraceExporter } = require('@opencensus/exporter-zipkin');
const { TraceContextFormat } = require('@opencensus/propagation-tracecontext');

const tracer = setupTracerAndExporters();

/** A function which makes requests and handles response. */
function makeRequest () {
// Root spans typically correspond to incoming requests, while child spans
// typically correspond to outgoing requests. Here, we have manually created
// the root span, which is created to track work that happens outside of the
// request lifecycle entirely.
tracer.startRootSpan({ name: 'octutorialsClient.makeRequest' }, rootSpan => {
http.get({
host: 'localhost',
port: 8080,
path: '/helloworld'
}, (response) => {
let body = [];
response.on('data', chunk => body.push(chunk));
response.on('end', () => {
console.log(body);
rootSpan.end();
});
});
});
}

function setupTracerAndExporters () {
const zipkinOptions = {
url: 'http://localhost:9411/api/v2/spans',
serviceName: 'opencensus_tutorial'
};

// Creates Zipkin exporter
const exporter = new ZipkinTraceExporter(zipkinOptions);

// Starts tracing and set sampling rate
const tracer = tracing.registerExporter(exporter).start({
samplingRate: 1, // For demo purposes, always sample
propagation: new TraceContextFormat()
}).tracer;

// Defines basedir and version
const basedir = path.dirname(require.resolve('http'));
const version = process.versions.node;

// Enables HTTP plugin: Method that enables the instrumentation patch.
plugin.enable(http, tracer, version, /** plugin options */{}, basedir);

return tracer;
}

makeRequest();
32 changes: 32 additions & 0 deletions examples/http/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"name": "http-example",
"version": "0.0.1",
"description": "Example of HTTP integration with OpenCensus",
"repository": "census-instrumentation/opencensus-node",
"keywords": [
"opencensus",
"http",
"tracing",
"stats",
"metrics"
],
"author": "OpenCensus Authors",
"license": "Apache-2.0",
"engines": {
"node": ">=6.0"
},
"scripts": {
"lint": "semistandard *.js",
"fix": "semistandard --fix"
},
"dependencies": {
"@opencensus/exporter-zipkin": "^0.0.9",
"@opencensus/instrumentation-http": "^0.0.9",
"@opencensus/nodejs": "^0.0.9",
"@opencensus/propagation-tracecontext": "^0.0.9",
"http": "*"
},
"devDependencies": {
"semistandard": "^13.0.1"
}
}
84 changes: 84 additions & 0 deletions examples/http/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/**
* Copyright 2019, OpenCensus 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
*
* gRPC://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.
*/

const path = require('path');
const http = require('http');
const tracing = require('@opencensus/nodejs');
const { plugin } = require('@opencensus/instrumentation-http');
const { ZipkinTraceExporter } = require('@opencensus/exporter-zipkin');
const { TraceContextFormat } = require('@opencensus/propagation-tracecontext');

const tracer = setupTracerAndExporters();

/** Starts a HTTP server that receives requests on sample server port. */
function startServer (port) {
// Creates a server
const server = http.createServer(handleRequest);
// Starts the server
server.listen(port, err => {
if (err) {
throw err;
}
console.log(`Node HTTP listening on ${port}`);
});
}

/** A function which handles requests and send response. */
function handleRequest (request, response) {
const span = tracer.startChildSpan('octutorials.handleRequest');
try {
let body = [];
request.on('error', err => console.log(err));
request.on('data', chunk => body.push(chunk));
request.on('end', () => {
// deliberately sleeping to mock some action.
setTimeout(() => {
span.end();
response.end('Hello World!');
}, 5000);
});
} catch (err) {
console.log(err);
span.end();
}
}

function setupTracerAndExporters () {
const zipkinOptions = {
url: 'http://localhost:9411/api/v2/spans',
serviceName: 'opencensus_tutorial'
};

// Creates Zipkin exporter
const exporter = new ZipkinTraceExporter(zipkinOptions);

// Starts tracing and set sampling rate
const tracer = tracing.registerExporter(exporter).start({
samplingRate: 1, // For demo purposes, always sample
propagation: new TraceContextFormat()
}).tracer;

// Defines basedir and version
const basedir = path.dirname(require.resolve('http'));
const version = process.versions.node;

// Enables HTTP plugin: Method that enables the instrumentation patch.
plugin.enable(http, tracer, version, /** plugin options */{}, basedir);

return tracer;
}

startServer(8080);
Binary file added examples/http/zipkin_http_nodejs.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
8 changes: 5 additions & 3 deletions packages/opencensus-instrumentation-http/src/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,8 +227,10 @@ export class HttpPlugin extends BasePlugin {
HttpPlugin.ATTRIBUTE_HTTP_ROUTE, requestUrl.path || '');
}

rootSpan.addAttribute(
HttpPlugin.ATTRIBUTE_HTTP_USER_AGENT, userAgent);
if (userAgent) {
rootSpan.addAttribute(
HttpPlugin.ATTRIBUTE_HTTP_USER_AGENT, userAgent);
}

rootSpan.addAttribute(
HttpPlugin.ATTRIBUTE_HTTP_STATUS_CODE,
Expand Down Expand Up @@ -326,7 +328,7 @@ export class HttpPlugin extends BasePlugin {
} else {
plugin.logger.debug('outgoingRequest starting a child span');
const span = plugin.tracer.startChildSpan(
{name: traceOptions.name, kind: traceOptions.kind});
traceOptions.name, traceOptions.kind);
return (plugin.getMakeRequestTraceFunction(request, options, plugin))(
span);
}
Expand Down

0 comments on commit 6cb24ee

Please sign in to comment.