Skip to content

OpenTelemetry: add trace example #1672

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions opentelemetry/trace/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# OpenTelemetry Trace API Node.js Samples
OpenTelemetry makes robust, portable telemetry a built-in feature of cloud-native software. OpenTelemetry provides a single set of APIs, libraries, agents, and collector services to capture distributed traces and metrics from your application.

## Table of Contents

* [Setup](#setup)
* [Samples](#samples)
* [Trace API](#trace-api)

## Setup

1. Read [Prerequisites][prereq] and [How to run a sample][run] first.
1. Install dependencies:

npm install


[prereq]: ../README.md#prerequisites
[run]: ../README.md#how-to-run-a-sample

## Samples

### Trace API

View the [documentation][trace_0_docs] or the [source code][trace_0_code].

__Usage:__ `node traces-quickstart.js`

[trace_0_docs]: https://open-telemetry.github.io/opentelemetry-js/
[trace_0_code]: traces-quickstart.js
33 changes: 33 additions & 0 deletions opentelemetry/trace/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"name": "opentelemetry-samples",
"description": "An example of exporting a traces from OpenTelemetry Node.js to Google Cloud Trace.",
"version": "0.0.1",
"private": true,
"license": "Apache-2.0",
"author": "Google Inc.",
"repository": {
"type": "git",
"url": "https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git"
},
"engines": {
"node": ">=8.0.0"
},
"scripts": {
"start": "node traces-quickstart.js",
"test": "repo-tools test run --cmd mocha -- system-test/*.test.js --timeout=5000 --exit"
},
"dependencies": {
"@opentelemetry/api": "0.5.2",
"@opentelemetry/tracing": "0.5.2",
"@opentelemetry/node": "0.5.2",
"@google-cloud/opentelemetry-cloud-trace-exporter": "0.1.0"
},
"devDependencies": {
"@google-cloud/nodejs-repo-tools": "^3.3.0",
"mocha": "^7.0.0"
},
"cloud-repo-tools": {
"requiresKeyFile": true,
"requiresProjectId": true
}
}
38 changes: 38 additions & 0 deletions opentelemetry/trace/system-test/traces-quickstart.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Copyright 2020 Google LLC
//
// 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
//
// http://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 assert = require('assert');
const childProcess = require('child_process');

it('Should throw an error without projectId', async () => {
process.env.GOOGLE_PROJECT_ID = '';

try {
await childProcess.execSync('node traces-quickstart.js');
assert.fail('Did not throw an error.');
} catch (err) {
assert.ok(err.message.includes('Unable to proceed without a Project ID'));
}
});

it('Should capture traces data and export it to backend', async () => {
process.env.GOOGLE_PROJECT_ID = 'fake-id';
process.env.KUBERNETES_SERVICE_HOST = 'localhost';
process.env.EXPORT_INTERVAL = 1;

const output = await childProcess.execSync('node traces-quickstart.js');
assert.ok(output.includes('Done recording traces.'));
});
75 changes: 75 additions & 0 deletions opentelemetry/trace/traces-quickstart.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
// Copyright 2020 Google LLC
//
// 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.
//

// [START opentelemetry_trace_samples]
'use strict';

// [START opentelemetry_trace_import]
const opentelemetry = require('@opentelemetry/api');
const {NodeTracerProvider} = require('@opentelemetry/node');
const {SimpleSpanProcessor} = require('@opentelemetry/tracing');
const {
StackdriverTraceExporter,
} = require('@google-cloud/opentelemetry-cloud-trace-exporter');
// [END opentelemetry_trace_import]

// [START setup_exporter]
// Enable OpenTelemetry exporters to export traces to Google Cloud Trace.
// Exporters use Application Default Credentials (ADCs) to authenticate.
// See https://developers.google.com/identity/protocols/application-default-credentials
// for more details.
// Expects ADCs to be provided through the environment as ${GOOGLE_APPLICATION_CREDENTIALS}
// A Stackdriver workspace is required and provided through the environment as ${GOOGLE_PROJECT_ID}
const projectId = process.env.GOOGLE_PROJECT_ID;

// GOOGLE_APPLICATION_CREDENTIALS are expected by a dependency of this code
// Not this code itself. Checking for existence here but not retaining (as not needed)
if (!projectId || !process.env.GOOGLE_APPLICATION_CREDENTIALS) {
throw Error('Unable to proceed without a Project ID');
}

const provider = new NodeTracerProvider();

// Initialize the exporter
const exporter = new StackdriverTraceExporter({projectId: projectId});

// Configure the span processor to send spans to the exporter
provider.addSpanProcessor(new SimpleSpanProcessor(exporter));

// [END setup_exporter]

// [START opentelemetry_trace_custom_span]

// Initialize the OpenTelemetry APIs to use the
// NodeTracerProvider bindings
opentelemetry.trace.setGlobalTracerProvider(provider);
const tracer = opentelemetry.trace.getTracer('basic');

// Create a span.
const span = tracer.startSpan('foo');

// Set attributes to the span.
span.setAttribute('key', 'value');

// Annotate our span to capture metadata about our operation
span.addEvent('invoking work');

// Be sure to end the span.
span.end();
// [END opentelemetry_trace_custom_span]

console.log('Done recording traces.');

// [END opentelemetry_trace_samples]