Pular para o conteúdo

Use the Aspire dashboard with Node.js apps

Este conteúdo não está disponível em sua língua ainda.

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.

To complete this tutorial, you need the following:

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:

  1. Create a new directory for your application:

    Terminal window
    mkdir aspire-nodejs-sample
    cd aspire-nodejs-sample
  2. Initialize a new Node.js project:

    Terminal window
    npm init -y
  3. Install Express.js:

    Terminal window
    npm install express
  4. 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}`);
    });
  5. 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"
    }
    }
  6. Test the application by running:

    Terminal window
    npm start
  7. Browse to the application at http://localhost:3000 in a web browser to verify it’s working.

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.

  1. 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 configuration
    const 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));
    });
  2. 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}`);
    });
  3. Restart your application:

    Terminal window
    npm start

To start the Aspire dashboard in standalone mode, run the following Docker command:

Terminal window
docker run --rm -it -p 18888:18888 -p 4317:18889 --name aspire-dashboard \
mcr.microsoft.com/dotnet/aspire-dashboard:latest

In 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.

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.

  1. Make some requests to your Node.js application:

    Terminal window
    curl http://localhost:3000/
    curl http://localhost:3000/api/weather
  2. Navigate to the Aspire dashboard at http://localhost:18888 and explore the different sections:

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.

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.

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:

JavaScript — app.js
// 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 tracer
const tracer = trace.getTracer('nodejs-app');
// Get a meter for custom metrics
const 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}`);
});

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.

Pergunta & RespondeColaboraComunidadeDiscutirVer