tencent cloud

Feedback

Connecting Node.js Applications Using the OpenTelemetry-JS Scheme (Recommended)

Last updated: 2024-06-19 16:31:30
    Note:
    OpenTelemetry is a collection of tools, APIs, and SDKs for monitoring, generating, collecting, and exporting telemetry data (metrics, logs, and traces) to help users analyze the performance and behavior of the software. For more information about OpenTelemetry, see the OpenTelemetry official website.
    The OpenTelemetry community is active, with rapid technological changes, and widely compatible with mainstream programming languages, components, and frameworks, making its link-tracing capability highly popular for cloud-native microservices and container architectures.
    This document will introduce how to connect Node.js applications using the OpenTelemetry-JS scheme through related operations.
    The OpenTelemetry-JS scheme provides automatic Event Tracking for common Node.js modules and frameworks, including Express, mysql, gRPC, etc., enabling link information reporting without needing to modify the code. For other modules and frameworks that support automatic Event Tracking, see the complete list provided by the OpenTelemetry community.

    Demo

    The demo code main.js provides 3 HTTP APIs through Express. Set up the corresponding MySQL and Redis services yourself or directly purchase Cloud Services.
    "use strict";
    
    const axios = require("axios").default;
    const express = require("express");
    const redis = require('./utils/redis');
    const dbHelper = require("./utils/db");
    const app = express();
    
    app.get("/remoteInvoke", async (req, res) => {
    const result = await axios.get("http://cloud.tencent.com");
    return res.status(200).send(result.data);
    });
    
    app.get("/redis", async(req, res) => {
    let queryRes = await redis.getKey("foo")
    res.json({ code: 200, result: queryRes})
    })
    
    app.get("/mysql", async(req, res) => {
    let select = select * from table_demo;
    await dbHelper.query(select);
    res.json({ code: 200, result: "mysql op ended"})
    })
    
    app.use(express.json());
    
    app.listen(8080, () => {
    console.log("Listening on http://localhost:8080");
    });
    

    Preliminary steps: Get the connect point and Token.

    1. Log in to the TCOP console.
    2. In the left menu column, select Application Performance Management > Application monitoring, and click Application list > Access application.
    3. In the Data access drawer frame that pops up on the right, click Node language.
    4. On the Access Node application page, select the region and business system you want to connect.
    5. Select Access protocol type as OpenTelemetry.
    6. Reporting method Choose your desired reporting method, and obtain your Access Point and Token.
    Note:
    Private network reporting: Using this reporting method, your service needs to run in the Tencent Cloud VPC. Through VPC connecting directly, you can avoid the security risks of public network communication and save on reporting traffic overhead.
    Public network reporting: If your service is deployed locally or in non-Tencent Cloud VPC, you can report data in this method. However, it involves security risks in public network communication and incurs reporting traffic fees.

    Connecting Node.js Applications

    Step 1: Install the required dependency packets.

    npm install --save @opentelemetry/api
    npm install --save @opentelemetry/auto-instrumentations-node

    Step 2: Add runtime parameters.

    Start the Node.js application with the following command:
    export OTEL_TRACES_EXPORTER="otlp"
    export OTEL_RESOURCE_ATTRIBUTES='token=<token>,hostName=<hostName>'
    export OTEL_EXPORTER_OTLP_PROTOCOL='grpc'
    export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT="<endpoint>"
    export OTEL_SERVICE_NAME="<serviceName>"
    export NODE_OPTIONS="--require @opentelemetry/auto-instrumentations-node/register"
    node main.js
    The corresponding field descriptions are as follows:
    <serviceName>: Application name. Multiple application processes connecting with the same serviceName are displayed as multiple instances under the same application in APM. The application name can be up to 63 characters and can only contain lowercase letters, digits, and the separator (-), and it must start with a lowercase letter and end with a digit or lowercase letter.
    <token>: The business system Token obtained in the preliminary steps.
    <hostName>: The hostname of this instance, which is the unique identifier of the application instance. It can usually be set to the IP address of the application instance.
    <endpoint>: The connect point obtained in the preliminary steps.
    The following content uses myService as the application name, myToken as the business system Token, 192.168.0.10 as the hostname, and http://pl-demo.ap-guangzhou.apm.tencentcs.com:4317 as the example connect point. The complete start-up command is:
    export OTEL_TRACES_EXPORTER="otlp"
    export OTEL_RESOURCE_ATTRIBUTES='token=myToken,hostName=192.168.0.10'
    export OTEL_EXPORTER_OTLP_PROTOCOL='grpc'
    export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT="http://pl-demo.ap-guangzhou.apm.tencentcs.com:4317"
    export OTEL_SERVICE_NAME="myService"
    export NODE_OPTIONS="--require @opentelemetry/auto-instrumentations-node/register"
    node main.js

    Connection Verification

    After the Node.js application is started, access the corresponding API through port 8080, for example, https://localhost:8080/. In the case of normal traffic, APM > Application monitoring > Application List will display the connected applications, and APM > Application monitoring > App details > Instance monitoring will display the connected application instances. Since there is some latency in processing observable data, if the application or instance is not found in the console after connecting, wait about 30 seconds.

    Custom Event Tracking (Optional)

    When automatic instrumentation does not meet your scenarios, or you need to add business layer instrumentation, you can see the following content and use the OpenTelemetry API to add custom instrumentation. This document only shows the most basic custom Event Tracking method. The OpenTelemetry community offers more flexible custom instrumentation methods, and you can see the OpenTelemetry community-provided Javascript Custom Event Tracking Documentation for specific methods.
    const opentelemetry = require("@opentelemetry/api")
    
    app.get("/attr", async(req, res) => {
    const tracer = opentelemetry.trace.getTracer(
    'my-service-tracer'
    );
    tracer.startActiveSpan('new internal span', span => {
    span.addEvent("Acquiring lock", {
    'log.severity':'error',
    'log.message':'data node found',
    })
    span.addEvent("Got lock, doing work...", {
    'log.severity':'11111',
    'log.message':'2222222',
    'log.message1':'3333333',
    })
    span.addEvent("Unlocking")
    span.end();
    });
    res.json({ code: 200, msg: "success" });
    })
    
    
    Contact Us

    Contact our sales team or business advisors to help your business.

    Technical Support

    Open a ticket if you're looking for further assistance. Our Ticket is 7x24 avaliable.

    7x24 Phone Support