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

Commit 6cb24ee

Browse files
authored
Add HTTP instrumentation guide (#369)
* Add HTTP instrumentation example * fix review comments
1 parent 04dcdbe commit 6cb24ee

File tree

6 files changed

+230
-3
lines changed

6 files changed

+230
-3
lines changed

examples/http/README.md

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Overview
2+
3+
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.
4+
5+
## Installation
6+
7+
```sh
8+
$ # from this directory
9+
$ npm install
10+
```
11+
12+
Setup [Zipkin Tracing](https://opencensus.io/codelabs/zipkin/#0)
13+
14+
## Run the Application
15+
16+
- Run the server
17+
18+
```sh
19+
$ # from this directory
20+
$ node ./server.js
21+
```
22+
23+
- Run the client
24+
25+
```sh
26+
$ # from this directory
27+
$ node ./client.js
28+
```
29+
30+
## Useful links
31+
- For more information on OpenCensus, visit: <https://opencensus.io/>
32+
- To checkout the OpenCensus for Node.js, visit: <https://github.com/census-instrumentation/opencensus-node>
33+
34+
## LICENSE
35+
36+
Apache License 2.0

examples/http/client.js

+73
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/**
2+
* Copyright 2019, OpenCensus Authors
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* gRPC://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
const path = require('path');
18+
const http = require('http');
19+
const tracing = require('@opencensus/nodejs');
20+
const { plugin } = require('@opencensus/instrumentation-http');
21+
const { ZipkinTraceExporter } = require('@opencensus/exporter-zipkin');
22+
const { TraceContextFormat } = require('@opencensus/propagation-tracecontext');
23+
24+
const tracer = setupTracerAndExporters();
25+
26+
/** A function which makes requests and handles response. */
27+
function makeRequest () {
28+
// Root spans typically correspond to incoming requests, while child spans
29+
// typically correspond to outgoing requests. Here, we have manually created
30+
// the root span, which is created to track work that happens outside of the
31+
// request lifecycle entirely.
32+
tracer.startRootSpan({ name: 'octutorialsClient.makeRequest' }, rootSpan => {
33+
http.get({
34+
host: 'localhost',
35+
port: 8080,
36+
path: '/helloworld'
37+
}, (response) => {
38+
let body = [];
39+
response.on('data', chunk => body.push(chunk));
40+
response.on('end', () => {
41+
console.log(body);
42+
rootSpan.end();
43+
});
44+
});
45+
});
46+
}
47+
48+
function setupTracerAndExporters () {
49+
const zipkinOptions = {
50+
url: 'http://localhost:9411/api/v2/spans',
51+
serviceName: 'opencensus_tutorial'
52+
};
53+
54+
// Creates Zipkin exporter
55+
const exporter = new ZipkinTraceExporter(zipkinOptions);
56+
57+
// Starts tracing and set sampling rate
58+
const tracer = tracing.registerExporter(exporter).start({
59+
samplingRate: 1, // For demo purposes, always sample
60+
propagation: new TraceContextFormat()
61+
}).tracer;
62+
63+
// Defines basedir and version
64+
const basedir = path.dirname(require.resolve('http'));
65+
const version = process.versions.node;
66+
67+
// Enables HTTP plugin: Method that enables the instrumentation patch.
68+
plugin.enable(http, tracer, version, /** plugin options */{}, basedir);
69+
70+
return tracer;
71+
}
72+
73+
makeRequest();

examples/http/package.json

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
{
2+
"name": "http-example",
3+
"version": "0.0.1",
4+
"description": "Example of HTTP integration with OpenCensus",
5+
"repository": "census-instrumentation/opencensus-node",
6+
"keywords": [
7+
"opencensus",
8+
"http",
9+
"tracing",
10+
"stats",
11+
"metrics"
12+
],
13+
"author": "OpenCensus Authors",
14+
"license": "Apache-2.0",
15+
"engines": {
16+
"node": ">=6.0"
17+
},
18+
"scripts": {
19+
"lint": "semistandard *.js",
20+
"fix": "semistandard --fix"
21+
},
22+
"dependencies": {
23+
"@opencensus/exporter-zipkin": "^0.0.9",
24+
"@opencensus/instrumentation-http": "^0.0.9",
25+
"@opencensus/nodejs": "^0.0.9",
26+
"@opencensus/propagation-tracecontext": "^0.0.9",
27+
"http": "*"
28+
},
29+
"devDependencies": {
30+
"semistandard": "^13.0.1"
31+
}
32+
}

examples/http/server.js

+84
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
/**
2+
* Copyright 2019, OpenCensus Authors
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* gRPC://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
const path = require('path');
18+
const http = require('http');
19+
const tracing = require('@opencensus/nodejs');
20+
const { plugin } = require('@opencensus/instrumentation-http');
21+
const { ZipkinTraceExporter } = require('@opencensus/exporter-zipkin');
22+
const { TraceContextFormat } = require('@opencensus/propagation-tracecontext');
23+
24+
const tracer = setupTracerAndExporters();
25+
26+
/** Starts a HTTP server that receives requests on sample server port. */
27+
function startServer (port) {
28+
// Creates a server
29+
const server = http.createServer(handleRequest);
30+
// Starts the server
31+
server.listen(port, err => {
32+
if (err) {
33+
throw err;
34+
}
35+
console.log(`Node HTTP listening on ${port}`);
36+
});
37+
}
38+
39+
/** A function which handles requests and send response. */
40+
function handleRequest (request, response) {
41+
const span = tracer.startChildSpan('octutorials.handleRequest');
42+
try {
43+
let body = [];
44+
request.on('error', err => console.log(err));
45+
request.on('data', chunk => body.push(chunk));
46+
request.on('end', () => {
47+
// deliberately sleeping to mock some action.
48+
setTimeout(() => {
49+
span.end();
50+
response.end('Hello World!');
51+
}, 5000);
52+
});
53+
} catch (err) {
54+
console.log(err);
55+
span.end();
56+
}
57+
}
58+
59+
function setupTracerAndExporters () {
60+
const zipkinOptions = {
61+
url: 'http://localhost:9411/api/v2/spans',
62+
serviceName: 'opencensus_tutorial'
63+
};
64+
65+
// Creates Zipkin exporter
66+
const exporter = new ZipkinTraceExporter(zipkinOptions);
67+
68+
// Starts tracing and set sampling rate
69+
const tracer = tracing.registerExporter(exporter).start({
70+
samplingRate: 1, // For demo purposes, always sample
71+
propagation: new TraceContextFormat()
72+
}).tracer;
73+
74+
// Defines basedir and version
75+
const basedir = path.dirname(require.resolve('http'));
76+
const version = process.versions.node;
77+
78+
// Enables HTTP plugin: Method that enables the instrumentation patch.
79+
plugin.enable(http, tracer, version, /** plugin options */{}, basedir);
80+
81+
return tracer;
82+
}
83+
84+
startServer(8080);

examples/http/zipkin_http_nodejs.png

188 KB
Loading

packages/opencensus-instrumentation-http/src/http.ts

+5-3
Original file line numberDiff line numberDiff line change
@@ -227,8 +227,10 @@ export class HttpPlugin extends BasePlugin {
227227
HttpPlugin.ATTRIBUTE_HTTP_ROUTE, requestUrl.path || '');
228228
}
229229

230-
rootSpan.addAttribute(
231-
HttpPlugin.ATTRIBUTE_HTTP_USER_AGENT, userAgent);
230+
if (userAgent) {
231+
rootSpan.addAttribute(
232+
HttpPlugin.ATTRIBUTE_HTTP_USER_AGENT, userAgent);
233+
}
232234

233235
rootSpan.addAttribute(
234236
HttpPlugin.ATTRIBUTE_HTTP_STATUS_CODE,
@@ -326,7 +328,7 @@ export class HttpPlugin extends BasePlugin {
326328
} else {
327329
plugin.logger.debug('outgoingRequest starting a child span');
328330
const span = plugin.tracer.startChildSpan(
329-
{name: traceOptions.name, kind: traceOptions.kind});
331+
traceOptions.name, traceOptions.kind);
330332
return (plugin.getMakeRequestTraceFunction(request, options, plugin))(
331333
span);
332334
}

0 commit comments

Comments
 (0)