Skip to content

Commit

Permalink
Migrate to Samples (#16085)
Browse files Browse the repository at this point in the history
* init commit for migration

* update

* fix some build

* file name

* address comments

* Rename BasicTracerNode.ts to basicTracerNode.ts

* Rename GRPCServer.ts to grpcServer.ts

* Rename HttpServer.ts to httpServer.ts

* clear up samples

* updates

* delete unused file

* yaml file

* update package version

* udpate build
  • Loading branch information
xiao-lix authored Jul 13, 2021
1 parent 7a0d595 commit f3cb8c1
Show file tree
Hide file tree
Showing 56 changed files with 1,675 additions and 2,351 deletions.
1,578 changes: 773 additions & 805 deletions common/config/rush/pnpm-lock.yaml

Large diffs are not rendered by default.

24 changes: 19 additions & 5 deletions sdk/monitor/monitor-opentelemetry-exporter/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@
"build:test": "echo skipped",
"build:node": "tsc -p . && rollup -c 2>&1",
"build": "npm run build:node && npm run build:browser && api-extractor run --local",
"check-format": "prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"",
"check-format": "prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"",
"extract-api": "tsc -p . && api-extractor run --local",
"format": "prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"",
"format": "prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"",
"lint:fix": "eslint package.json api-extractor.json src test --ext .ts --fix --fix-type [problem,suggestion]",
"lint": "eslint package.json api-extractor.json src test --ext .ts -f html -o telemetry-exporter-lintReport.html || exit 0",
"test": "npm run test:node && npm run test:browser",
Expand All @@ -35,7 +35,8 @@
"test-opentelemetry-versions": "node test-opentelemetry-versions.js 2>&1",
"prepare": "npm run build",
"pack": "npm pack 2>&1",
"build:samples": "echo Skipped.",
"build:samples": "echo Obsolete.",
"execute:samples": "dev-tool samples run samples-dev",
"docs": "typedoc --excludePrivate --excludeNotExported --excludeExternals --stripInternal --mode file --out ./dist/docs ./src"
},
"engines": {
Expand Down Expand Up @@ -73,12 +74,25 @@
}
]
},
"//sampleConfiguration": {
"productName": "Azure Monitor Trace Exporter",
"productSlugs": [
"azure-monitor"
],
"requiredResources": {
"Azure Application Insights workspace instance": "https://docs.microsoft.com/azure/azure-monitor/app/app-insights-overview"
}
},
"devDependencies": {
"@azure/dev-tool": "^1.0.0",
"@azure/eslint-plugin-azure-sdk": "^3.0.0",
"@microsoft/api-extractor": "7.7.11",
"@opentelemetry/instrumentation": "0.22.0",
"@opentelemetry/instrumentation-http": "0.22.0",
"@opentelemetry/node": "0.22.0",
"@types/mocha": "^7.0.2",
"@types/node": "^12.0.0",
"dotenv": "^8.2.0",
"eslint": "^7.15.0",
"eslint-plugin-node": "^11.1.0",
"execa": "^3.3.0",
Expand All @@ -90,8 +104,8 @@
"rollup": "^1.16.3",
"sinon": "^9.0.2",
"ts-node": "^9.0.0",
"typescript": "~4.2.0",
"typedoc": "0.15.2"
"typedoc": "0.15.2",
"typescript": "~4.2.0"
},
"dependencies": {
"@azure/core-http": "^2.0.0",
Expand Down
1 change: 1 addition & 0 deletions sdk/monitor/monitor-opentelemetry-exporter/sample.env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
APPLICATIONINSIGHTS_CONNECTION_STRING=<your connection string>
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

/**
* This example shows how to use
* [@opentelemetry/tracing](https://github.com/open-telemetry/opentelemetry-js/tree/master/packages/opentelemetry-tracing)
* to instrument a simple Node.js application - e.g. a batch job.
*
* @summary use opentelemetry tracing to instrument a Node.js application. Basic use of Tracing in Node.js application.
*/

import * as opentelemetry from "@opentelemetry/api";
import { Resource } from "@opentelemetry/resources";
import { ResourceAttributes } from "@opentelemetry/semantic-conventions";
import { BasicTracerProvider, SimpleSpanProcessor } from "@opentelemetry/tracing";
import { AzureMonitorTraceExporter } from "@azure/monitor-opentelemetry-exporter";

// Load the .env file if it exists
import * as dotenv from "dotenv";
dotenv.config();

const provider = new BasicTracerProvider({
resource: new Resource({
[ResourceAttributes.SERVICE_NAME]: "basic-service"
})
});

// Configure span processor to send spans to the exporter
const exporter = new AzureMonitorTraceExporter({
connectionString:
process.env["APPLICATIONINSIGHTS_CONNECTION_STRING"] || "<your connection string>"
});
provider.addSpanProcessor(new SimpleSpanProcessor(exporter as any));

/**
* Initialize the OpenTelemetry APIs to use the BasicTracerProvider bindings.
*
* This registers the tracer provider with the OpenTelemetry API as the global
* tracer provider. This means when you call API methods like
* `opentelemetry.trace.getTracer`, they will use this tracer provider. If you
* do not register a global tracer provider, instrumentation which calls these
* methods will receive no-op implementations.
*/
provider.register();
const tracer = opentelemetry.trace.getTracer("example-basic-tracer-node");

export async function main() {
// Create a span. A span must be closed.
const parentSpan = tracer.startSpan("main");
for (let i = 0; i < 10; i += 1) {
doWork(parentSpan);
}
// Be sure to end the span.
parentSpan.end();

// flush and close the connection.
exporter.shutdown();
}

function doWork(parent: opentelemetry.Span) {
// Start another span. In this example, the main method already started a
// span, so that'll be the parent span, and this will be a child span.
const ctx = opentelemetry.trace.setSpan(opentelemetry.context.active(), parent);
const span = tracer.startSpan("doWork", undefined, ctx);

// simulate some random work.
for (let i = 0; i <= Math.floor(Math.random() * 40000000); i += 1) {
// empty
}

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

// Annotate our span to capture metadata about our operation
span.addEvent("invoking doWork");

span.end();
}

main().catch((error) => {
console.error("An error occurred:", error);
process.exit(1);
});
129 changes: 129 additions & 0 deletions sdk/monitor/monitor-opentelemetry-exporter/samples-dev/httpSample.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

/**
* OpenTelemetry HTTP Instrumentation allows the user to
* automatically collect trace data and export them to
* the backend of choice (we can use Zipkin or Jaeger for this example),
* to give observability to distributed systems.
*
* This is a simple example that demonstrates tracing HTTP request from client to server.
* The example shows key aspects of tracing such as
* - Root Span (on Client)
* - Child Span (on Client)
* - Child Span from a Remote Parent (on Server)
* - SpanContext Propagation (from Client to Server)
* - Span Events
* - Span Attributes
*
* @summary demonstrates OpenTelemetry http Instrumentation. It is about how OpenTelemetry will instrument the Node.js native http module.
*/
import api from "@opentelemetry/api";
import { registerInstrumentations } from "@opentelemetry/instrumentation";
import { NodeTracerProvider } from "@opentelemetry/node";
import { SimpleSpanProcessor, Tracer } from "@opentelemetry/tracing";
import { AzureMonitorTraceExporter } from "@azure/monitor-opentelemetry-exporter";
import { HttpInstrumentation } from "@opentelemetry/instrumentation-http";

// Load the .env file if it exists
import * as dotenv from "dotenv";
dotenv.config();

/*********************************************************************
* OPEN TELEMETRY SETUP
**********************************************************************/
let serverTracer: Tracer;
let clientTracer: Tracer;
setupOpenTelemetry();

// Open Telemetry setup need to happen before http library is loaded
import http from "http";

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

/** A function which handles requests and send response. */
function handleRequest(request: any, response: any) {
const currentSpan = api.trace.getSpan(api.context.active());
if (currentSpan) {
// display traceid in the terminal
console.log(`traceid: ${currentSpan.spanContext().traceId}`);
}
const span = serverTracer.startSpan("handleRequest", {
kind: 1, // server
attributes: { key: "value" }
});
// Annotate our span to capture metadata about the operation
span.addEvent("invoking handleRequest");

const body = [];
request.on("error", (err: Error) => console.log(err));
request.on("data", (chunk: string) => body.push(chunk));
request.on("end", () => {
// deliberately sleeping to mock some action.
setTimeout(() => {
span.end();
response.end("Hello World!");
}, 2000);
});
}

startServer(8080);

/*********************************************************************
* HTTP CLIENT SETUP
**********************************************************************/
/** A function which makes requests and handles response. */
function makeRequest() {
// span corresponds to outgoing requests. Here, we have manually created
// the span, which is created to track work that happens outside of the
// request lifecycle entirely.
const span = clientTracer.startSpan("makeRequest");
api.context.with(api.trace.setSpan(api.context.active(), span), () => {
http.get(
{
host: "localhost",
port: 8080
},
(response) => {
const body: any = [];
response.on("data", (chunk) => body.push(chunk));
response.on("end", () => {
console.log(body.toString());
span.end();
});
}
);
});
}
makeRequest();

function setupOpenTelemetry() {
const provider = new NodeTracerProvider();
const exporter = new AzureMonitorTraceExporter({
connectionString:
process.env["APPLICATIONINSIGHTS_CONNECTION_STRING"] || "<your connection string>"
});

provider.addSpanProcessor(new SimpleSpanProcessor(exporter as any));

// Initialize the OpenTelemetry APIs to use the NodeTracerProvider bindings
provider.register();

registerInstrumentations({
// // when boostraping with lerna for testing purposes
instrumentations: [new HttpInstrumentation()]
});
serverTracer = provider.getTracer("serverTracer");
clientTracer = provider.getTracer("clientTracer");
}

This file was deleted.

Binary file not shown.

This file was deleted.

Loading

0 comments on commit f3cb8c1

Please sign in to comment.