Use the Aspire dashboard with Node.js apps
Questi contenuti non sono ancora disponibili nella tua lingua.
The Aspire dashboard provides a great user experience for viewing telemetry, and is available as a standalone container image that can be used with any OpenTelemetry-enabled app. In this article, you’ll learn how to:
- Start the Aspire dashboard in standalone mode.
- Use the Aspire dashboard with a Node.js app.
Prerequisites
Section titled “Prerequisites”To complete this tutorial, you need the following:
- Container runtime.
- You can use an alternative container runtime, but the commands in this article are for Docker.
- Node.js 18 or higher locally installed.
- A sample application.
Sample application
Section titled “Sample application”This tutorial uses an Express.js application to demonstrate the integration. You can either create a new Express.js app or use an existing Node.js application.
To create a new Express.js application:
-
Create a new directory for your application:
Terminal window mkdir aspire-nodejs-samplecd aspire-nodejs-sample -
Initialize a new Node.js project:
Terminal window npm init -y -
Install Express.js:
Terminal window npm install express -
Create a basic Express.js application by creating an app.js file with Express server code.
JavaScript — app.js const express = require('express');const app = express();const port = process.env.PORT || 3000;app.get('/', (req, res) => {console.log('Received request for home page');res.json({message: 'Hello from Node.js!',timestamp: new Date().toISOString()});});app.get('/api/weather', (req, res) => {const weather = [{ city: 'Seattle', temperature: 72, condition: 'Cloudy' },{ city: 'Portland', temperature: 68, condition: 'Rainy' },{ city: 'San Francisco', temperature: 65, condition: 'Foggy' },{ city: 'Los Angeles', temperature: 78, condition: 'Sunny' }];console.log('Received request for weather data');res.json(weather);});app.listen(port, () => {console.log(`Server running at http://localhost:${port}`);}); -
Replace the entire package.json with the following content:
JSON — package.json {"name": "aspire-nodejs-sample","version": "1.0.0","description": "Sample Node.js application for Aspire dashboard tutorial","main": "app.js","scripts": {"start": "node app.js"},"dependencies": {"express": "^4.18.0","@opentelemetry/api": "^1.8.0","@opentelemetry/sdk-node": "^0.203.0","@opentelemetry/exporter-trace-otlp-grpc": "^0.203.0","@opentelemetry/exporter-metrics-otlp-grpc": "^0.203.0","@opentelemetry/auto-instrumentations-node": "^0.44.0"}} -
Test the application by running:
Terminal window npm start -
Browse to the application at
http://localhost:3000in a web browser to verify it’s working.
Adding OpenTelemetry
Section titled “Adding OpenTelemetry”To use the Aspire dashboard with your Node.js app, you need to install the OpenTelemetry SDK and exporter. The OpenTelemetry SDK provides the API for instrumenting your application, and the exporter sends telemetry data to the Aspire dashboard.
-
Create a new file called tracing.js to configure OpenTelemetry.
JavaScript — tracing.js const { NodeSDK } = require('@opentelemetry/sdk-node');const { getNodeAutoInstrumentations } = require('@opentelemetry/auto-instrumentations-node');const { OTLPTraceExporter } = require('@opentelemetry/exporter-trace-otlp-grpc');const { OTLPMetricExporter } = require('@opentelemetry/exporter-metrics-otlp-grpc');const { PeriodicExportingMetricReader } = require('@opentelemetry/sdk-metrics');// Configure the OTLP endpoint - this should match your dashboard configurationconst otlpEndpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4317';const sdk = new NodeSDK({traceExporter: new OTLPTraceExporter({url: otlpEndpoint,}),metricReader: new PeriodicExportingMetricReader({exporter: new OTLPMetricExporter({url: otlpEndpoint,}),exportIntervalMillis: 5000,}),instrumentations: [getNodeAutoInstrumentations({'@opentelemetry/instrumentation-fs': {enabled: false,},})],});sdk.start();console.log('OpenTelemetry started successfully');process.on('SIGTERM', () => {sdk.shutdown().then(() => console.log('Tracing terminated')).catch((error) => console.log('Error terminating tracing', error)).finally(() => process.exit(0));}); -
Update your app.js to import the tracing configuration at the very beginning.
JavaScript — app.js // This must be imported first!require('./tracing');const express = require('express');const app = express();const port = process.env.PORT || 3000;app.get('/', (req, res) => {console.log('Received request for home page');res.json({message: 'Hello from Node.js!',timestamp: new Date().toISOString()});});app.get('/api/weather', (req, res) => {const weather = [{ city: 'Seattle', temperature: 72, condition: 'Cloudy' },{ city: 'Portland', temperature: 68, condition: 'Rainy' },{ city: 'San Francisco', temperature: 65, condition: 'Foggy' },{ city: 'Los Angeles', temperature: 78, condition: 'Sunny' }];console.log('Received request for weather data');res.json(weather);});app.listen(port, () => {console.log(`Server running at http://localhost:${port}`);}); -
Restart your application:
Terminal window npm start
Start the Aspire dashboard
Section titled “Start the Aspire dashboard”To start the Aspire dashboard in standalone mode, run the following Docker command:
docker run --rm -it -p 18888:18888 -p 4317:18889 --name aspire-dashboard \ mcr.microsoft.com/dotnet/aspire-dashboard:latestdocker run --rm -it -p 18888:18888 -p 4317:18889 --name aspire-dashboard ` mcr.microsoft.com/dotnet/aspire-dashboard:latestIn the Docker logs, the endpoint and key for the dashboard are displayed. Copy the key and navigate to http://localhost:18888 in a web browser. Enter the key to log in to the dashboard.
View telemetry in the dashboard
Section titled “View telemetry in the dashboard”After starting both the dashboard and your Node.js application, you can view telemetry data by making requests to your application and observing the results in the dashboard.
-
Make some requests to your Node.js application:
Terminal window curl http://localhost:3000/curl http://localhost:3000/api/weather -
Navigate to the Aspire dashboard at
http://localhost:18888and explore the different sections:
Traces
Section titled “Traces”The Traces page shows distributed traces for HTTP requests. Each request to your Express.js application creates a trace that you can explore to see the request flow and timing information.
Metrics
Section titled “Metrics”The Metrics page displays various metrics collected from your Node.js application, including HTTP request metrics, Node.js runtime metrics, and custom metrics if you choose to add them.
Adding custom telemetry
Section titled “Adding custom telemetry”You can enhance your application with custom spans, logs, and metrics by updating your application code. Update the app.js file to include custom telemetry:
// This must be imported first!require('./tracing');
const express = require('express');const { trace, metrics } = require('@opentelemetry/api');
const app = express();const port = process.env.PORT || 3000;
// Get a tracerconst tracer = trace.getTracer('nodejs-app');
// Get a meter for custom metricsconst meter = metrics.getMeter('nodejs-app');const requestCounter = meter.createCounter('http_requests_total', { description: 'Total number of HTTP requests',});
app.get('/', (req, res) => { const span = tracer.startSpan('handle-home-request');
try { console.log('Received request for home page'); requestCounter.add(1, { route: '/', method: 'GET' });
span.setAttributes({ 'http.route': '/', 'user.agent': req.get('User-Agent') || 'unknown' });
res.json({ message: 'Hello from Node.js!', timestamp: new Date().toISOString() }); } finally { span.end(); }});
app.get('/api/weather', (req, res) => { const span = tracer.startSpan('handle-weather-request');
try { const weather = [ { city: 'Seattle', temperature: 72, condition: 'Cloudy' }, { city: 'Portland', temperature: 68, condition: 'Rainy' }, { city: 'San Francisco', temperature: 65, condition: 'Foggy' }, { city: 'Los Angeles', temperature: 78, condition: 'Sunny' } ];
console.log('Received request for weather data'); requestCounter.add(1, { route: '/api/weather', method: 'GET' });
span.setAttributes({ 'http.route': '/api/weather', 'weather.cities_count': weather.length });
res.json(weather); } finally { span.end(); }});
app.listen(port, () => { console.log(`Server running at http://localhost:${port}`);});Next steps
Section titled “Next steps”You have successfully used the Aspire dashboard with a Node.js application. To learn more about the Aspire dashboard, see the Aspire dashboard overview and how to orchestrate a Node.js application with the Aspire AppHost.
To learn more about OpenTelemetry instrumentation for Node.js applications, see the OpenTelemetry JavaScript documentation.