|
| 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 | + * http://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 | +/** Example showing how to directly create a child span and add annotations. */ |
| 18 | +const tracing = require('@opencensus/nodejs'); |
| 19 | +const { ZipkinTraceExporter } = require('@opencensus/exporter-zipkin'); |
| 20 | + |
| 21 | +// 1. Get the global singleton Tracer object |
| 22 | +// 2. Configure 100% sample rate, otherwise, few traces will be sampled. |
| 23 | +const tracer = tracing.start({ samplingRate: 1 }).tracer; |
| 24 | + |
| 25 | +// 3. Configure exporter to export traces to Zipkin. |
| 26 | +tracer.registerSpanEventListener(new ZipkinTraceExporter({ |
| 27 | + url: 'http://localhost:9411/api/v2/spans', |
| 28 | + serviceName: 'node.js-quickstart' |
| 29 | +})); |
| 30 | + |
| 31 | +function main () { |
| 32 | + // 4. Create a span. A span must be closed. |
| 33 | + // For any of the web frameworks for which we provide built-in plugins (http, |
| 34 | + // grpc, mongodb etc), a root span is automatically started whenever an |
| 35 | + // incoming request is received (in other words, all middleware already runs |
| 36 | + // within a root span). |
| 37 | + tracer.startRootSpan({ name: 'main' }, rootSpan => { |
| 38 | + for (let i = 0; i < 10; i++) { |
| 39 | + doWork(); |
| 40 | + } |
| 41 | + |
| 42 | + // Be sure to call rootSpan.end(). |
| 43 | + rootSpan.end(); |
| 44 | + }); |
| 45 | + |
| 46 | + // Add short delay to allow data to export. |
| 47 | + setTimeout(() => { |
| 48 | + console.log('done.'); |
| 49 | + }, 2000); |
| 50 | +} |
| 51 | + |
| 52 | +function doWork () { |
| 53 | + // 5. Start another span. In this example, the main method already started a |
| 54 | + // span, so that'll be the parent span, and this will be a child span. |
| 55 | + const span = tracer.startChildSpan('doWork'); |
| 56 | + |
| 57 | + console.log('doing busy work'); |
| 58 | + for (let i = 0; i <= 40000000; i++) {} // short delay |
| 59 | + |
| 60 | + // 6. Annotate our span to capture metadata about our operation |
| 61 | + span.addAnnotation('invoking doWork'); |
| 62 | + for (let i = 0; i <= 20000000; i++) {} // short delay |
| 63 | + |
| 64 | + span.end(); |
| 65 | +} |
| 66 | + |
| 67 | +main(); |
0 commit comments