Skip to content

Commit 72e8c2b

Browse files
author
Mark Wolff
authored
[Monitor]: add OpenTelemetry samples (Azure#10218)
* chore(monitor): add samples * remove non-basic storage examples * add manual root span example * add sample gantt chart * remove browser blurb * fix readme linting * refactor samples for latest package name * remove rel links * fix typos
1 parent 8b2bccd commit 72e8c2b

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

41 files changed

+1584
-2
lines changed

sdk/monitor/opentelemetry-exporter-azure-monitor/README.md

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@ provider.register();
3838

3939
// Create an exporter instance
4040
const exporter = new AzureMonitorTraceExporter({
41-
logger: provider.logger,
4241
instrumentationKey: "ikey"
4342
});
4443

@@ -61,7 +60,7 @@ Coming Soon
6160

6261
## Examples
6362

64-
Coming soon // TODO: Update this with link to samples when we have some
63+
For complete samples of a few champion scenarios, see the [`samples/`](https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/monitor/opentelemetry-exporter-azure-monitor/samples/) folder.
6564

6665
## Key concepts
6766

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# Getting started with samples
2+
3+
Code cloned from [azure-sdk-for-js/storage-blob/samples](https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/storage/storage-blob/samples).
4+
5+
## `@microsoft/opentelemetry-exporter-azure-monitor`
6+
7+
All changes required to enable exporting trace data to Azure Monitor were made in `tracing.ts` / `tracing.js`.
8+
9+
In order for auto-instrumentation to take effect, `tracing` must be imported **before** you `import` or `require` any other module into your application!.
10+
11+
![AzureMonitorImage](./images/storage.png)
12+
13+
## Get account credentials of your storage account
14+
15+
- In the [Azure Portal](https://portal.azure.com), go to **Dashboard > Storage > _your-storage-account_**.
16+
- Note down the "AccountName", "AccountKey" obtained at **Access keys** and "AccountSAS" from **Shared access signature** under **Settings** tab.
17+
Before running any of the samples, update with the credentials you have noted down above.
18+
19+
### Authenticating with Azure Active Directory
20+
21+
If you have [registered an application](https://docs.microsoft.com/azure/active-directory/develop/quickstart-register-app) with an Azure Active Directory tenant, you can [assign it to an RBAC role](https://docs.microsoft.com/azure/storage/common/storage-auth-aad) in your Azure Storage account. This enables you to use the Azure.Identity library to authenticate with Azure Storage as shown in the [azureAdAuth.ts sample](https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/storage/storage-blob/samples/typescript/src/azureAdAuth.ts).
22+
23+
## JavaScript sample
24+
25+
Copy the sample to your samples folder and use `node` to run it.
26+
27+
```bash
28+
node sample.js
29+
```
30+
31+
## TypeScript sample
32+
33+
If you don't have Typescript installed, then use `npm` to install it first.
34+
35+
```bash
36+
npm install -g typescript
37+
```
38+
39+
One way to run Typescript samples is to use `ts-node`. To run `ts-node`, run the below in your sample folder
40+
41+
```bash
42+
npx ts-node sample.ts
43+
```
44+
45+
## Browser sample
46+
47+
Currently, the Azure Monitor OpenTelemetry Exporter only supports Node.js environments. This sample will be updated once browser support becomes available.
48+
49+
<!-- Running these samples in the browser requires a bundler. While we give examples using Webpack, any bundler will do!
50+
51+
First, install webpack and webpack-cli.
52+
53+
```bash
54+
npm install --save-dev webpack webpack-cli
55+
```
56+
57+
Next, run webpack on the sample code to produce an optimized browser bundle.
58+
59+
```bash
60+
npx webpack sample.js
61+
```
62+
63+
This will produce `dist/main.js`. Reference this file in an HTML file script tag and open the file in a browser to run the sample.
64+
65+
```html
66+
<script src="./dist/main.js"></script>
67+
``` -->
242 KB
Loading
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
---
2+
page_type: sample
3+
languages:
4+
- javascript
5+
products:
6+
- azure
7+
- azure-storage
8+
urlFragment: storage-blob-javascript
9+
---
10+
11+
# Azure Storage Blob client library samples for JavaScript
12+
13+
These sample programs show how to use the JavaScript client libraries for Azure Storage Blobs in some common scenarios.
14+
15+
| **File Name** | **Description** |
16+
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
17+
| [basic.js][basic] | authenticate with the service using an account name & key (or anonymously with a SAS URL); create and delete containers; create, list, and download a blob |
18+
19+
## Prerequisites
20+
21+
The sample are compatible with Node.js >= 8.0.0, except for the samples that use the async `for await` syntax, which require Node.js >= 10.0.0.
22+
23+
You need [an Azure subscription][freesub] and [an Azure Storage account][azstorage] to run these sample programs. Samples retrieve credentials to access the storage account from environment variables. Alternatively, edit the source code to include the appropriate credentials. See each individual sample for details on which environment variables/credentials it requires to function.
24+
25+
Adapting the samples to run in the browser requires some additional consideration. For details, please see the [package README][package].
26+
27+
## Setup
28+
29+
To run the samples using the published version of the package:
30+
31+
1. Install the dependencies using `npm`:
32+
33+
```bash
34+
npm install
35+
```
36+
37+
2. Edit the file `sample.env`, adding the correct credentials to access the Azure service and run the samples. Then rename the file from `sample.env` to just `.env`. The sample programs will read this file automatically.
38+
39+
3. Run whichever samples you like (note that some samples may require additional setup, see the table above):
40+
41+
```bash
42+
node basic.js
43+
```
44+
45+
Alternatively, run a single sample with the correct environment variables set (step 3 is not required if you do this), for example (cross-platform):
46+
47+
```bash
48+
npx cross-env ACCOUNT_NAME="<account name>" ACCOUNT_KEY="<account key>" node basic.js
49+
```
50+
51+
## Next Steps
52+
53+
Take a look at our [API Documentation][apiref] for more information about the APIs that are available in the clients.
54+
55+
[basic]: https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/storage/storage-blob/samples/javascript/basic.js
56+
[apiref]: https://docs.microsoft.com/javascript/api/@azure/storage-blob
57+
[azstorage]: https://docs.microsoft.com/azure/storage/common/storage-account-overview
58+
[freesub]: https://azure.microsoft.com/free/
59+
[package]: https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/storage/storage-blob/README.md
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
// Copyright (c) Microsoft Corporation.
2+
// Licensed under the MIT license.
3+
4+
// Load the .env file if it exists
5+
require("dotenv").config();
6+
7+
// Setup tracing before importing anything else
8+
require("./tracing");
9+
10+
/*
11+
Setup: Enter your storage account name and shared key in main()
12+
*/
13+
14+
const { BlobServiceClient, StorageSharedKeyCredential } = require("@azure/storage-blob");
15+
16+
async function main() {
17+
// Enter your storage account name and shared key
18+
const account = process.env.ACCOUNT_NAME || "";
19+
const accountKey = process.env.ACCOUNT_KEY || "";
20+
21+
// Use StorageSharedKeyCredential with storage account and account key
22+
// StorageSharedKeyCredential is only avaiable in Node.js runtime, not in browsers
23+
const sharedKeyCredential = new StorageSharedKeyCredential(account, accountKey);
24+
25+
// ONLY AVAILABLE IN NODE.JS RUNTIME
26+
// DefaultAzureCredential will first look for Azure Active Directory (AAD)
27+
// client secret credentials in the following environment variables:
28+
//
29+
// - AZURE_TENANT_ID: The ID of your AAD tenant
30+
// - AZURE_CLIENT_ID: The ID of your AAD app registration (client)
31+
// - AZURE_CLIENT_SECRET: The client secret for your AAD app registration
32+
//
33+
// If those environment variables aren't found and your application is deployed
34+
// to an Azure VM or App Service instance, the managed service identity endpoint
35+
// will be used as a fallback authentication source.
36+
// const defaultAzureCredential = new DefaultAzureCredential();
37+
38+
// You can find more TokenCredential implementations in the [@azure/identity](https://www.npmjs.com/package/@azure/identity) library
39+
// to use client secrets, certificates, or managed identities for authentication.
40+
41+
// Use AnonymousCredential when url already includes a SAS signature
42+
// const anonymousCredential = new AnonymousCredential();
43+
44+
// List containers
45+
const blobServiceClient = new BlobServiceClient(
46+
// When using AnonymousCredential, following url should include a valid SAS or support public access
47+
`https://${account}.blob.core.windows.net`,
48+
sharedKeyCredential
49+
);
50+
51+
let i = 1;
52+
for await (const container of blobServiceClient.listContainers()) {
53+
console.log(`Container ${i++}: ${container.name}`);
54+
}
55+
56+
// Create a container
57+
const containerName = `newcontainer${new Date().getTime()}`;
58+
const containerClient = blobServiceClient.getContainerClient(containerName);
59+
60+
const createContainerResponse = await containerClient.create();
61+
console.log(`Create container ${containerName} successfully`, createContainerResponse.requestId);
62+
63+
// Create a blob
64+
const content = "hello";
65+
const blobName = "newblob" + new Date().getTime();
66+
const blockBlobClient = containerClient.getBlockBlobClient(blobName);
67+
const uploadBlobResponse = await blockBlobClient.upload(content, Buffer.byteLength(content));
68+
console.log(`Upload block blob ${blobName} successfully`, uploadBlobResponse.requestId);
69+
70+
// List blobs
71+
i = 1;
72+
for await (const blob of containerClient.listBlobsFlat()) {
73+
console.log(`Blob ${i++}: ${blob.name}`);
74+
}
75+
76+
// Get blob content from position 0 to the end
77+
// In Node.js, get downloaded data by accessing downloadBlockBlobResponse.readableStreamBody
78+
// In browsers, get downloaded data by accessing downloadBlockBlobResponse.blobBody
79+
const downloadBlockBlobResponse = await blockBlobClient.download(0);
80+
console.log(
81+
"Downloaded blob content",
82+
await streamToString(downloadBlockBlobResponse.readableStreamBody)
83+
);
84+
85+
// Delete container
86+
await containerClient.delete();
87+
88+
console.log("deleted container");
89+
}
90+
91+
// A helper method used to read a Node.js readable stream into string
92+
async function streamToString(readableStream) {
93+
return new Promise((resolve, reject) => {
94+
const chunks = [];
95+
readableStream.on("data", (data) => {
96+
chunks.push(data.toString());
97+
});
98+
readableStream.on("end", () => {
99+
resolve(chunks.join(""));
100+
});
101+
readableStream.on("error", reject);
102+
});
103+
}
104+
105+
main().catch((err) => {
106+
console.error("Error running sample:", err.message);
107+
});
108+
109+
console.log("Waiting batched span processor to export batched spans");
110+
setTimeout(() => {
111+
console.log("Terminating");
112+
}, 6000);
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
{
2+
"name": "azure-storage-blob-samples-js",
3+
"private": true,
4+
"version": "0.1.0",
5+
"description": "Azure Storage Blob client library samples for TypeScript",
6+
"engine": {
7+
"node": ">=8.0.0"
8+
},
9+
"repository": {
10+
"type": "git",
11+
"url": "git+https://github.com/Azure/azure-sdk-for-js.git"
12+
},
13+
"keywords": [
14+
"Azure",
15+
"Storage",
16+
"Blob",
17+
"Node.js",
18+
"JavaScript"
19+
],
20+
"author": "Microsoft Corporation",
21+
"license": "MIT",
22+
"bugs": {
23+
"url": "https://github.com/Azure/azure-sdk-for-js/issues"
24+
},
25+
"homepage": "https://github.com/Azure/azure-sdk-for-js#readme",
26+
"sideEffects": false,
27+
"dependencies": {
28+
"@azure/abort-controller": "latest",
29+
"@azure/identity": "latest",
30+
"@azure/storage-blob": "latest",
31+
"@microsoft/opentelemetry-exporter-azure-monitor": "latest",
32+
"@opentelemetry/node": "latest",
33+
"dotenv": "^8.2.0"
34+
},
35+
"devDependencies": {
36+
"rimraf": "^3.0.0"
37+
}
38+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
APPLICATIONINSIGHTS_CONNECTION_STRING=
2+
3+
# Used in most samples. Retrieve these values from a storage account in the Azure Portal.
4+
ACCOUNT_NAME=<storage-account-name>
5+
ACCOUNT_KEY=<storage-account-key>
6+
7+
# Used for withConnString
8+
STORAGE_CONNECTION_STRING=<storage-account-connection-string>
9+
10+
# Used for the advanced and anonymousCred tests. Create a SAS token for a storage account in the Azure Portal.
11+
ACCOUNT_SAS=<shared-access-signature>
12+
13+
# Used to authenticate using Azure AD as a service principal for role-based authentication.
14+
#
15+
# See the documentation for `EnvironmentCredential` at the following link:
16+
# https://docs.microsoft.com/javascript/api/@azure/identity/environmentcredential
17+
AZURE_TENANT_ID=<AD tenant id or name>
18+
AZURE_CLIENT_ID=<ID of the user/service principal to authenticate as>
19+
AZURE_CLIENT_SECRET=<client secret used to authenticate to Azure AD>
20+
21+
# To run the proxyAuth sample, set up an HTTP proxy and enter your information:
22+
# HTTP_PROXY=http://localhost:3128
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { AzureMonitorTraceExporter } from "@microsoft/opentelemetry-exporter-azure-monitor";
2+
import { NodeTracerProvider } from "@opentelemetry/node";
3+
import { BatchSpanProcessor } from "@opentelemetry/tracing";
4+
import * as azureSdkTracing from "@azure/core-tracing";
5+
6+
const provider = new NodeTracerProvider();
7+
8+
const azureExporter = new AzureMonitorTraceExporter({
9+
connectionString: process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "ikey"
10+
});
11+
12+
provider.addSpanProcessor(
13+
new BatchSpanProcessor(azureExporter, {
14+
bufferSize: 1000, // 1000 spans
15+
bufferTimeout: 15000 // 15 seconds
16+
})
17+
);
18+
19+
provider.register();
20+
21+
azureSdkTracing.setTracer(provider.getTracer("example tracer"));
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
dist

0 commit comments

Comments
 (0)