跳到主要内容
跳到主要内容

Node.js

ClickStack 使用 OpenTelemetry 标准来采集遥测数据(日志 logs、指标 metrics、追踪 traces 和异常 exceptions)。Traces 通过自动插桩自动生成,因此无需手动插桩即可从 tracing 中获益。

本指南集成了:

  • Logs
  • Metrics
  • Traces
  • Exceptions

开始使用

安装 HyperDX OpenTelemetry Instrumentation 包

使用以下命令安装 ClickStack OpenTelemetry 包

npm install @hyperdx/node-opentelemetry 

初始化 SDK

要初始化 SDK,需要在应用程序入口文件的顶部调用 init 函数。

const HyperDX = require('@hyperdx/node-opentelemetry');

HyperDX.init({
    apiKey: 'YOUR_INGESTION_API_KEY',
    service: 'my-service'
});

这将自动从你的 Node.js 应用程序中采集跟踪、指标和日志数据。

设置日志采集

默认情况下,会自动采集 console.* 日志。如果您使用的是 winstonpino 等 logger,则需要在 logger 中添加一个 transport,将日志发送到 ClickStack。 如果您使用的是其他类型的 logger,欢迎联系我们,或者根据需要使用我们的平台集成(例如 Kubernetes)。

如果您使用 winston 作为 logger,需要在 logger 中添加以下 transport。

    import winston from 'winston';
    import * as HyperDX from '@hyperdx/node-opentelemetry';

    const logger = winston.createLogger({
      level: 'info',
      format: winston.format.json(),
      transports: [
        new winston.transports.Console(),
        HyperDX.getWinstonTransport('info', { // Send logs info and above
          detectResources: true,
        }),
      ],
    });

    export default logger;

设置错误收集

ClickStack SDK 可以自动捕获应用程序中未捕获的异常和错误,并附带完整的堆栈跟踪和代码上下文。

要启用此功能,您需要将以下代码添加到应用程序错误处理中间件链路的末尾,或者使用 recordException 函数手动捕获异常。

const HyperDX = require('@hyperdx/node-opentelemetry');
HyperDX.init({
    apiKey: 'YOUR_INGESTION_API_KEY',
    service: 'my-service'
});
const app = express();

// Add your routes, etc.

// Add this after all routes,
// but before any and other error-handling middlewares are defined
HyperDX.setupExpressErrorHandler(app);

app.listen(3000);

故障排除

如果在使用 SDK 时遇到问题,可以通过将 OTEL_LOG_LEVEL 环境变量设置为 debug 来启用详细日志输出。

export OTEL_LOG_LEVEL=debug

高级埋点配置

捕获控制台日志

默认情况下,ClickStack SDK 会捕获控制台日志。可以通过将环境变量 HDX_NODE_CONSOLE_CAPTURE 设置为 0 来禁用此功能。

export HDX_NODE_CONSOLE_CAPTURE=0

Attach user information or metadata

To easily tag all events related to a given attribute or identifier (ex. user id or email), you can call the setTraceAttributes function which will tag every log/span associated with the current trace after the call with the declared attributes. It's recommended to call this function as early as possible within a given request/trace (ex. as early in an Express middleware stack as possible).

This is a convenient way to ensure all logs/spans are automatically tagged with the right identifiers to be searched on later, instead of needing to manually tag and propagate identifiers yourself.

userId, userEmail, userName, and teamName will populate the sessions UI with the corresponding values, but can be omitted. Any other additional values can be specified and used to search for events.

import * as HyperDX from '@hyperdx/node-opentelemetry';

app.use((req, res, next) => {
  // 从请求中获取用户信息...

  // 将用户信息附加到当前跟踪
  HyperDX.setTraceAttributes({
    userId,
    userEmail,
  });

  next();
});

Make sure to enable beta mode by setting HDX_NODE_BETA_MODE environment variable to 1 or by passing betaMode: true to the init function to enable trace attributes.

export HDX_NODE_BETA_MODE=1

Google Cloud Run

If you're running your application on Google Cloud Run, Cloud Trace automatically injects sampling headers into incoming requests, currently restricting traces to be sampled at 0.1 requests per second for each instance.

The @hyperdx/node-opentelemetry package overwrites the sample rate to 1.0 by default.

To change this behavior, or to configure other OpenTelemetry installations, you can manually configure the environment variables OTEL_TRACES_SAMPLER=parentbased_always_on and OTEL_TRACES_SAMPLER_ARG=1 to achieve the same result.

To learn more, and to force tracing of specific requests, please refer to the Google Cloud Run documentation.

Auto-instrumented libraries

The following libraries will be automatically instrumented (traced) by the SDK:

Alternative installation

Run the Application with ClickStack OpenTelemetry CLI

Alternatively, you can auto-instrument your application without any code changes by using the opentelemetry-instrument CLI or using the Node.js --require flag. The CLI installation exposes a wider range of auto-instrumented libraries and frameworks.

HYPERDX_API_KEY='<YOUR_INGESTION_KEY>' OTEL_SERVICE_NAME='<YOUR_APP_NAME>' npx opentelemetry-instrument index.js

The OTEL_SERVICE_NAME environment variable is used to identify your service in the HyperDX app, it can be any name you want.

Enabling exception capturing

To enable uncaught exception capturing, you'll need to set the HDX_NODE_EXPERIMENTAL_EXCEPTION_CAPTURE environment variable to 1.

HDX_NODE_EXPERIMENTAL_EXCEPTION_CAPTURE=1

随后,如需自动捕获来自 Express、Koa 的异常或手动捕获异常,请按照上文 设置错误收集 一节中的说明进行配置。

自动插桩的库

通过上述安装方法,以下库将被自动插桩(用于追踪):