Skip to content

Commit

Permalink
feat: add OTLP metrics sample
Browse files Browse the repository at this point in the history
Signed-off-by: David Ashpole <[email protected]>
  • Loading branch information
dashpole committed Jan 17, 2025
1 parent f8b5157 commit 66c1ebb
Show file tree
Hide file tree
Showing 8 changed files with 1,270 additions and 81 deletions.
1,160 changes: 1,079 additions & 81 deletions package-lock.json

Large diffs are not rendered by default.

17 changes: 17 additions & 0 deletions samples/otlpmetricexport/.prettierrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Copyright 2025 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.

module.exports = {
...require('gts/.prettierrc.json')
}
43 changes: 43 additions & 0 deletions samples/otlpmetricexport/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Overview

This example shows how to send metrics to an OTLP *(OpenTelemetry Protocol)* endpoint that is protected by GCP authentication. The sample showcases the metric export using gRPC

## Installation

```sh
# from root of repo, build all packages
npm install
```

## Run the Application

```sh
# export necessary OTEL environment variables
export OTEL_RESOURCE_ATTRIBUTES="gcp.project_id=<project-id>"
export OTEL_EXPORTER_OTLP_ENDPOINT=<endpoint>

# run the app - this starts app at port 8080
# the start script uses gRPC to export
cd samples/otlpmetricexport && npm run start
```

## View metrics

https://console.cloud.google.com//monitoring/metrics-explorer?project=your-project-id

1. Select the Metric from the dropdown. You should see it under the resource "Generic Task":

<img width="1584" alt="choose metric type" src="images/choose-metric-type.png?raw=true"/>

2. View the timeseries:

<img width="1584" alt="view timeseries" src="images/metric-timeseries.png?raw=true"/>


## Useful links
- For more information on OpenTelemetry, visit: <https://opentelemetry.io/>
- For more information on metrics, visit: <https://opentelemetry.io/docs/concepts/signals/metrics/>

## LICENSE

Apache License 2.0
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
35 changes: 35 additions & 0 deletions samples/otlpmetricexport/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"name": "otlp-metrics-export",
"version": "0.1.0",
"private": true,
"author": "Google Inc.",
"license": "Apache-2.0",
"scripts": {
"start": "ts-node ./src/index.ts",
"lint": "gts lint",
"clean": "gts clean",
"fix": "gts fix",
"compile": "tsc",
"test": "",
"pretest": "npm run compile"
},
"keywords": [],
"dependencies": {
"@opentelemetry/api": "1.9.0",
"@opentelemetry/auto-instrumentations-node": "0.50.0",
"@opentelemetry/exporter-metrics-otlp-grpc": "0.53.0",
"@opentelemetry/resources": "1.26.0",
"@opentelemetry/sdk-node": "0.53.0",
"@opentelemetry/sdk-metrics": "1.26.0",
"@grpc/grpc-js": "1.11.3",
"express": "4.21.0",
"google-auth-library": "9.14.1",
"axios": "1.7.7"
},
"devDependencies": {
"gts": "5.3.1",
"typescript": "4.9.5",
"ts-node": "10.9.2"
},
"description": "This example shows how to send metrics to an OTLP *(OpenTelemetry Protocol)* endpoint that is protected by GCP authentication over gRPC."
}
84 changes: 84 additions & 0 deletions samples/otlpmetricexport/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// Copyright 2025 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.

import * as opentelemetry from '@opentelemetry/sdk-node';
import { AuthClient, GoogleAuth } from 'google-auth-library';
import { credentials } from '@grpc/grpc-js';
import {
getResourceDetectors as getResourceDetectorsFromEnv,
} from '@opentelemetry/auto-instrumentations-node';
import {
metrics,
diag,
DiagConsoleLogger,
} from '@opentelemetry/api';
import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-grpc';
import { PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics';

async function getAuthenticatedClient(): Promise<AuthClient> {
const auth: GoogleAuth = new GoogleAuth({
scopes: 'https://www.googleapis.com/auth/cloud-platform',
});
return await auth.getClient();
}

diag.setLogger(
new DiagConsoleLogger(),
opentelemetry.core.getEnv().OTEL_LOG_LEVEL
);


// Express App that exports traces via gRPC with protobuf
async function main() {
const authenticatedClient: AuthClient = await getAuthenticatedClient();

const sdk = new opentelemetry.NodeSDK({
metricReader: new PeriodicExportingMetricReader({
// Export metrics every 10 seconds. 5 seconds is the smallest sample period allowed by
// Cloud Monitoring.
exportIntervalMillis: 10_000,
exporter: new OTLPMetricExporter({
credentials: credentials.combineChannelCredentials(
credentials.createSsl(),
credentials.createFromGoogleCredential(authenticatedClient)
),
}),
}),
resourceDetectors: getResourceDetectorsFromEnv(),
});
sdk.start();

// Create a meter
const meter = metrics.getMeterProvider().getMeter("metrics-sample");

// Create a counter instrument
const counter = meter.createCounter("metric_name");
// Record a measurement
counter.add(10, { key: "value" });

// Wait for the metric to be exported
await new Promise((resolve) => {
setTimeout(resolve, 11_000);
});

// Gracefully shut down the SDK to flush telemetry when the program exits
process.on('SIGTERM', () => {
sdk
.shutdown()
.then(() => diag.debug('OpenTelemetry SDK terminated'))
.catch(error => diag.error('Error terminating OpenTelemetry SDK', error));
});
}

main();
12 changes: 12 additions & 0 deletions samples/otlpmetricexport/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"extends": "gts/tsconfig-google.json",
"compilerOptions": {
"rootDir": ".",
"outDir": "build",
"esModuleInterop": true
},
"include": [
"src/**/*.ts",
"test/**/*.ts"
]
}

0 comments on commit 66c1ebb

Please sign in to comment.